Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();
Related
Hellos,
Can anyone help me look at this code; its generating an error."java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1"
//Code
private void btnBatchPayrollActionPerformed(java.awt.event.ActionEvent evt) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "arrowsdb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try{
Object newInstance = Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
Statement st = conn.createStatement();
// int rows = st.executeUpdate("INSERT INTO employeeinfo SELECT * FROM employeeinfo");
//int rows = st.executeUpdate("INSERT INTO payroll(employeeid,fname,basic,housing,transport,medical) SELECT * FROM employeeinfo('EmployeeId','Name,Basic','Housing','Transport','Medical')");
//INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;
int rows = st.executeUpdate("INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;)");
if (rows == 0) {
System.out.println("Don't add any row!");
} else {
System.out.println(rows + " row(s)affected.");
conn.close();
}
}
catch(ClassNotFoundException | SQLException e)
{
System.out.println(e);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(BatchPayroll.class.getName()).log(Level.SEVERE, null, ex);
}
}
Thx
fm
You had an extra right parenthesis in your SQL. I haven't tested this, because I don't have these SQL tables, but I think this is correct. I used the MySQL 8 documentation to verify the format.
It also helps to format your code and SQL, so it's easier to spot errors like unbalanced parenthesis.
private void btnBatchPayrollActionPerformed(java.awt.event.ActionEvent evt) {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "arrowsdb";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Object newInstance = Class.forName(driver).newInstance();
Connection conn = DriverManager.getConnection(url + dbName, userName, password);
Statement st = conn.createStatement();
// int rows = st.executeUpdate("INSERT INTO employeeinfo SELECT * FROM
// employeeinfo");
// int rows = st.executeUpdate("INSERT INTO
// payroll(employeeid,fname,basic,housing,transport,medical) SELECT * FROM
// employeeinfo('EmployeeId','Name,Basic','Housing','Transport','Medical')");
// INSERT INTO payroll (employeeid,fname,basic,housing,transport,medical) SELECT
// EmployeeId,Name,Basic,Housing,Transport,Medical FROM employeeinfo;
int rows = st.executeUpdate(
"INSERT INTO payroll " +
" (employeeid, fname, basic, housing, transport, medical) " +
"SELECT EmployeeId, Name, Basic, Housing, Transport, Medical " +
"FROM employeeinfo; ");
if (rows == 0) {
System.out.println("Don't add any row!");
} else {
System.out.println(rows + " row(s)affected.");
conn.close();
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println(e);
} catch (InstantiationException | IllegalAccessException ex) {
Logger.getLogger(BatchPayroll.class.getName()).log(Level.SEVERE, null, ex);
}
I'm trying to send an increase count variable of a picture (which is increased by just increasing +1 everytime a new session hits a picture). I'm getting the following error message however, i'm checking for an empty result set. My thought process is that I can try to select the picturesNo that has been called and if it can't find that pictureNo we simply insert the first count to the table, and if it can find it, we then update this.
Error message:
"SQLException: Illegal operation on empty result set."
Code to increase the count for the session
HttpSession session = request.getSession() ;
Integer counter = (Integer) session.getAttribute("counter");
String accCount = (String) session.getAttribute("attributeKey") ;
String url = "http://localhost:8080/techfore";
String encodedURL = url + ";jsessionid=" + request.getSession().getId();
if (accCount == null || encodedURL == null) { // New session?
response.sendRedirect("/techfore/WelcomePage");
}
else{
if(counter == 0) {
counter = new Integer(counter.intValue() + 1);
session.setAttribute("counter", counter);
}
}
Utilities.initalCount(out, pictureName, counter);
Code to run the queries
public static void initalCount(PrintWriter out, String pictureName, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
}
try {
Statement stmt = con.createStatement();
String query0;
ResultSet rs1;
query0="SELECT PictureNo FROM Statistics WHERE PictureNo = (SELECT PictureNo FROM Pictures WHERE ShortName = '"+pictureName+"')";
rs1 = stmt.executeQuery(query0);
if(rs1.next()){
//yes exist
String description = rs1.getString("Description");
int pictureNo = rs1.getInt("PictureNo");
IncreaseCount(out, pictureNo, accessCount);
}
else {
//if rs is null insert
int pictureNo = rs1.getInt("PictureNo");
AddCount(out, pictureNo, accessCount);
}
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void AddCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="INSERT INTO Statistics VALUES "+pictureNo+","+accessCount+" ";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void IncreaseCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="UPDATE Statistics SET AccessCount = "+accessCount+" + 1 WHERE PictureNo = "+pictureNo+"";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
New insert
query="INSERT INTO Statistics VALUES (SELECT PictureNo FROM Pictures WHERE FileName = '"+pictureName+"'),"+accessCount+" ";
Hello guys how can I check duplicate inputs (adding students) and how to prevent it. It says that when i create a table the inputs that I've been inserting the database is all a duplicate which is obviously not. In line with that how can I detect and check of the inserted input is a duplicate of the previous inputs.This is the first output in my console This is the continuation
Here is my code:
Main.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.sql.Statement;
public class Main {
public static void main (String args[]) throws Exception {
StudentDAO x1= new StudentDAO();
x1.getConnection();
x1.makeTable(); //create Table
x1.addstud("1","Yves Francisco", "2000000001","5","CpE","Male");
x1.addstud("2","Lance Eco", "2000000002","5","CpE","Male");
x1.addstud("3","Karlos Castillo", "2000000003","5","CpE","Male");
x1.addstud("4","Glenn Bordonada", "2000000004","5","ECE","Male");
x1.addstud("5","JM Enriquez", "2000000005","5","ECE","Male");
x1.addstud("6","John Martinez", "2000000006","2","ECE","Male");
x1.addstud("7","Timothy Tolentino", "2000000007","4","IT","Male");
x1.addstud("8","Kyle Dacaymat", "2000000008","3","CpE","Male");
x1.addstud("9","Dom Benedictos", "2000000009","1","IT","Male");
x1.addstud("10","Lance Roque", "2000000010","1","ECE","Male");
x1.addstud("11", "Vegeta", "2000000011", "1", "ME", "Male"); // added Student
//x1.addstud("12", "Vegeta", "2000000011", "1", "ME", "Male"); // pang check if entered input is a duplicate of a field of studName, studNumber, etc.
//x1.delstud(); // delete student
//x1.updstuddb();
x1.showdb();
}
}
StudentDAO.java
//import java.util.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
//import java.sql.ArrayList;
public class StudentDAO {
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public void showdb() throws Exception
{
try {
Connection con = getConnection();
String query = "SELECT *FROM studinfo;";
PreparedStatement showstuddb= con.prepareStatement(query);
ResultSet rs = showstuddb.executeQuery();
System.out.println("Showing Database.....................");
System.out.println("============================================================# THE CONTENT OF THE DATABASE #============================================================");
while (rs.next())
{
String idko = rs.getObject(1).toString();
String ngalan = rs.getObject(2).toString();
String numko=rs.getObject(3).toString();
String baitang=rs.getObject(4).toString();
String kurso=rs.getObject(5).toString();
String kasarian=rs.getObject(6).toString();
System.out.println("My ID number is: "+ idko + " Name is: " + ngalan + " Student Number is: " + numko + " Year/Level is: "+ baitang +" Course is: " + kurso + " Sex is: " + kasarian);
}
showstuddb.close();
System.out.println("Nothing follows.....................");
con.close();
}
catch (Exception e)
{
System.out.println("Error on showing contents of database!!!" + e.getMessage());
}
}
public void updstuddb () throws Exception
{
try {
Connection con = getConnection();
String query = "UPDATE studinfo SET studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=? WHERE studid=?";
PreparedStatement studup = con.prepareStatement(query);
studup.setString(1, "Kakarot"); //This will be the replacement
studup.setString(2, "2000000020");
studup.setString(3, "2");
studup.setString(4, "IT");
studup.setString(5, "dafq");
studup.setString(6, "1");// The unique element among the content of the database which is used to determine which is to update
studup.executeUpdate();
System.out.println("THE LIST HAS BEEN UPDATED ############################################################");
studup.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error in updating the database!!!" + e.getMessage());
}
}
public void delstud()
{
try {
Connection con = getConnection();
String query = "DELETE FROM studinfo WHERE studid=?";
PreparedStatement userdel = con.prepareStatement(query);
userdel.setString(1, "12"); // To determine what to delete in the Database
//userdel.setString(1, "2000000002");
//userdel.setString(1, "2000000003");
//userdel.setString(1, "2000000004");
//userdel.setString(1, "2000000005");
//userdel.setString(1, "2000000006");
//userdel.setString(1, "2000000007");
//userdel.setString(1, "2000000008");
//userdel.setString(1, "2000000009");
//userdel.setString(1, "2000000010");
userdel.execute();
userdel.close();
System.out.println("Data is now deleted!!!");
con.close();
}
catch (Exception e)
{
System.out.println("Error!!!. Data is not deleted " + e.getMessage());
}
}
public void addstud(String studid, String studName, String studNum, String studYrLvl, String studKors, String studGender) throws Exception
{
//String var1 = "Yves Francisco";
//String num1 = "2000000001";
//String num2 = "5";
//String var2 = "CpE";
//String var3 = "Male";
try {
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studid, studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?,?)");
int y=1;
posted.setString(y++, studid);
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();
//con.close();
}
catch (Exception e)
{
System.out.println("Error on adding columns!!!" + e.getMessage());
}
finally
{
System.out.println("Insert Successful!");
}
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
}
public void makeTable() throws Exception
{
try
{
Connection con= getConnection();
PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS studinfo (studid INT NOT NULL AUTO_INCREMENT PRIMARY KEY, studName varchar(255), studNum varchar(30), studYrLvl varchar(2), studKors varchar(30), studGender varchar(10));");
create.executeUpdate();
System.out.println("TABLE IS CREATED!!!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
create.close();
con.close();
}
catch (Exception e)
{
System.out.println("Error on creating table!!. Table not created!"+e.getMessage());
}
finally
{
System.out.println("Table created!");
};
}
public Connection getConnection () throws Exception {
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/mydb";
String username= "root";
String password = "root";
Class.forName(driver);
Connection conn= DriverManager.getConnection(url, username, password);
System.out.println("You are now Connected!!");
return conn; // Return if it is successfully connected!
}
catch (Exception e)
{
System.out.println("Connection not Established!"+e.getMessage());
}
return null; // Return if unsuccessful
}
}
The problem is not a duplicate value in your table, the problem is that you have a mistake in your code.
I wouldn't do it the way you do, because if you use a Try-Catch, anyway there is a problem or a mistake in your code (looking for duplicates) it will answer that you have a duplicate.
Otherwise, even if you have thousands of duplicates, if you don't get an error you won't get a duplicate.
Anyways, the mistake you have in your code is that you don't give any value to the checkdup prepared statement, you should change it to something like this:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
while (rs.next())
{
boolean dup1=rs.getObject(2).equals(studName);
boolean dup2=rs.getObject(3).equals(studNum);
boolean dup3=rs.getObject(4).equals(studYrLvl);
boolean dup4=rs.getObject(5).equals(studKors);
boolean dup5=rs.getObject(6).equals(studGender);
System.out.println("The name you entered is: " + dup1 + " The student number you entered is: " + dup2 + " The Yr/Lvl you entered: " + dup3 + " The Course you entered: " + dup4 + " The Sex you entered is: " + dup5);
}
con.close();
}
catch (Exception e)
{
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
EDIT
There is an easy way to look for duplicates, you just count how many you have like in this code:
//FOR DUPLICATE INPUTS!!!!!!!!!!!!!!!!
try
{
Connection con = getConnection();
String query = "SELECT studName, studNum, studYrLvl, studKors, studGender FROM studinfo WHERE studName=?, studNum=?, studYrLvl=?, studKors=?, studGender=?";
PreparedStatement checkdup = con.prepareStatement(query);
checkdup.setString(1, studName);
checkdup.setString(2, studNum);
checkdup.setString(3, studYrLvl);
checkdup.setString(4, studKors);
checkdup.setString(5, studGender);
ResultSet rs=checkdup.executeQuery();
int dup=0;
while (rs.next())
{
dup+=1;
}
if (dup>1 ) {
System.out.println("You entered a duplicate value!!. Try Again! ");
System.out.println("Take note that the entered Duplicate value is entered in the Database");
System.out.println("Remove the duplicate value using delstud() method!!!");
}
con.close();
}
catch (Exception e)
{
System.out.println("There is an error ");
}
In your INSERT statement, you also need to change things. The studid is an autoincrement column, so you don't have to put it in your INSERT. It should be like:
Connection con = getConnection();
PreparedStatement posted= con.prepareStatement("INSERT INTO studinfo (studName, studNum, studYrLvl, studKors, studGender) VALUES (?,?,?,?,?)");
int y=1;
posted.setString(y++, studName);
posted.setString(y++, studNum);
posted.setString(y++, studYrLvl);
posted.setString(y++, studKors);
posted.setString(y++, studGender);
posted.executeUpdate(); // Manipulate or Update table
posted.close();
I created a database with one table in MySQL:
CREATE DATABASE iac_enrollment_system;
USE iac_enrollment_system;
CREATE TABLE course(
course_code CHAR(7),
course_desc VARCHAR(255) NOT NULL,
course_chair VARCHAR(255),
PRIMARY KEY(course_code)
);
I tried to insert a record using Java:
// STEP 1: Import required packages
import java.sql.*;
import java.util.*;
public class SQLInsert {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/iac_enrollment_system";
// Database credentials
static final String USER = "root";
static final String PASS = "1234";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Scanner scn = new Scanner(System.in);
String course_code = null, course_desc = null, course_chair = null;
try {
// STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// STEP 3: Open a connection
System.out.print("\nConnecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println(" SUCCESS!\n");
// STEP 4: Ask for user input
System.out.print("Enter course code: ");
course_code = scn.nextLine();
System.out.print("Enter course description: ");
course_desc = scn.nextLine();
System.out.print("Enter course chair: ");
course_chair = scn.nextLine();
// STEP 5: Excute query
System.out.print("\nInserting records into table...");
stmt = conn.createStatement();
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
System.out.println(" SUCCESS!\n");
} catch(SQLException se) {
se.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if(stmt != null)
conn.close();
} catch(SQLException se) {
}
try {
if(conn != null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
}
}
System.out.println("Thank you for your patronage!");
}
}
The output appears to return successfully:
But when I select from MySQL, the inserted record is blank:
Why is it inserting a blank record?
no that cannot work(not with real data):
String sql = "INSERT INTO course " +
"VALUES (course_code, course_desc, course_chair)";
stmt.executeUpdate(sql);
change it to:
String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
"VALUES (?, ?, ?)";
Create a PreparedStatment with that sql and insert the values with index:
PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate();
this can also be done like this if you don't want to use prepared statements.
String sql = "INSERT INTO course(course_code,course_desc,course_chair)"+"VALUES('"+course_code+"','"+course_desc+"','"+course_chair+"');"
Why it didnt insert value is because you were not providing values, but you were providing names of variables that you have used.
This should work for any table, instead of hard-coding the columns.
//Source details
String sourceUrl = "jdbc:oracle:thin:#//server:1521/db";
String sourceUserName = "src";
String sourcePassword = "***";
// Destination details
String destinationUserName = "dest";
String destinationPassword = "***";
String destinationUrl = "jdbc:mysql://server:3306/db";
Connection srcConnection = getSourceConnection(sourceUrl, sourceUserName, sourcePassword);
Connection destConnection = getDestinationConnection(destinationUrl, destinationUserName, destinationPassword);
PreparedStatement sourceStatement = srcConnection.prepareStatement("SELECT * FROM src_table ");
ResultSet rs = sourceStatement.executeQuery();
rs.setFetchSize(1000); // not needed
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement destStatement = destConnection.prepareStatement(
"INSERT INTO dest_table ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)
)
{
int count = 0;
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++) {
destStatement.setObject(i, rs.getObject(i));
}
destStatement.addBatch();
count++;
}
destStatement.executeBatch(); // you will see all the rows in dest once this statement is executed
System.out.println("done " + count);
}
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
I have one application in which I need to delete table if exit in Microsoft Access Database.
I saw the code here. The table name which I want to delete is data_table and the access database file name is local_entry
so where I need to change the code so it work for my application.
public void testDropTable () throws SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");
Statement stmt = con.createStatement();
ResultSet checkTable = con.getMetaData().getTables(null, null, "POI", null);
String tableName = null;
while (checkTable.next())
{
System.out.println("In here");
tableName = checkTable.getString("TABLE_NAME");
System.out.println(tableName);
}
if (tableName != null){
try {
String dropTable = "DROP TABLE ";
String[] tables = DB_TABLE;
for (int i = 0; i < tables.length; i++){
String stringCode = new String();
stringCode = stringCode + tables[i];
System.out.println(dropTable + tables[i]);
// Drop each table in the array.
int temp = stmt.executeUpdate(dropTable + tables[i]);
}
}
catch (Exception e) {
System.err.println("Exception in testDropTable (): \n"
+ "Drop Table testDropTable threw an exception: " +(e.getMessage()));
}
}
else{
con.close();
}
}
I think I need to change this two line:
String dropTable = "DROP TABLE ";
String[] tables = DB_TABLE;
can I change DROP TABLE to data_table and what about second line. What is this DB_TABLE
I change the whole code by this way but till problem is there:
public void testDropTable () throws SQLException{
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
Connection con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");
Statement stmt = con.createStatement();
ResultSet checkTable = con.getMetaData().getTables(null, null, "POI", null);
String tableName = null;
while (checkTable.next())
{
System.out.println("In here");
tableName = checkTable.getString("data_table");
System.out.println(tableName);
}
if (tableName != null){
try {
String dropTable = "DROP TABLE ";
String[] tables = {"data_table"};
for (int i = 0; i < tables.length; i++){
String stringCode = new String();
stringCode = stringCode + tables[i];
System.out.println(dropTable + tables[i]);
// Drop each table in the array.
int temp = stmt.executeUpdate(dropTable + tables[i]);
}
}
catch (Exception e) {
System.err.println("Exception in testDropTable (): \n"
+ "Drop Table testDropTable threw an exception: " +(e.getMessage()));
}
}
else{
con.close();
}
}
try this code
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");
Statement stmt = con.createStatement();
// Specify the type of object; in this case we want tables
String[] types = {"TABLE"};
ResultSet checkTable = con.getMetaData().getTables(null, null, "%", types);
String tableName = null;
while (checkTable.next())
{
System.out.println("In here");
tableName = checkTable.getString(3)
System.out.println(tableName);
// check if the table 'data_table' exist in your database
if (tableName.equals("data_table"){
try {
//drop the table if present
int temp = stmt.executeUpdate("DROP TABLE " + tableName);
break;
}
catch (Exception e) {
System.err.println("Exception in testDropTable (): \n"
+ "Drop Table testDropTable threw an exception: " +(e.getMessage()));
}
}
}
con.close;
for more information visit here Metadata
Drop table table name; is the command to drop the table in your database.
Try to replace the DB_TABLE with data_table.
String dropTable = "DROP TABLE ";
String[] tables = data_table;
try this
public void testDropTable () throws SQLException{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");
Statement stmt = con.createStatement();
ResultSet checkTable = con.getMetaData().getTables(null, null, "POI", null);
String tableName = null;
while (checkTable.next())
{
System.out.println("In here");
tableName = checkTable.getString("data_table");
System.out.println(tableName);
}
if (tableName != null){
try {
String dropTable = "DROP TABLE ";
String[] tables = tableName;
for (int i = 0; i < tables.length; i++){
String stringCode = new String();
stringCode = stringCode + tables[i];
System.out.println(dropTable + tables[i]);
// Drop each table in the array.
int temp = stmt.executeUpdate(dropTable + tables[i]);
}
}
catch (Exception e) {
System.err.println("Exception in testDropTable (): \n"
+ "Drop Table testDropTable threw an exception: " +(e.getMessage()));
}
}
else{
con.close();
}
}
For anybody interested in this question, i removed the while loop statement in the accepted answer and reduced the code to:
public void testDropTable() throws SQLException, ClassNotFoundException {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:MsAccessDSN");
Statement stmt = con.createStatement();
String[] tables = {"data_table"};
for (String table : tables) {
try {
stmt.executeUpdate("DROP TABLE " + table);
} catch (SQLException e) {
System.err.println("Exception in testDropTable (): \n"
+ "Drop Table testDropTable threw an exception: " +(e.getMessage()));
}
}
con.close();
}