i am creating simple sales system. i have to get the last insert id but i couldn't get the id.when i tried the code i got the error of the console
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
i attached the code below what i tried so far
try{
int lastinsertid=0;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root","");
String query = " insert into sales_product (product, price)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(query);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet rs = preparedStmt.executeQuery();
if (rs.next()) {
lastinsertid = (int) rs.getLong(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
}
catch(ClassNotFoundException coe)
{
System.out.println("odbc driver not found");
}
catch(SQLException sqe)
{
System.out.println(sqe);
}
You need to add Statement.RETURN_GENERATED_KEYS in con1.prepareStatement(query) that would result that you can get the generated key. You also should use only one of the following methods:
executeQuery
executeUpdate
Because there is no reason, to use booth methods.
After you done that you can get it like that:
...
PreparedStatement preparedStmt = con1.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
preparedStmt.setString (1, txtproduct.getText());
preparedStmt.setString (2, txtprice.getText());
preparedStmt.executeUpdate();
ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
if (generatedKeyResult.next()) {
lastinsertid = generatedKeyResult.getInt(1);
}
System.out.println("Inserted record's ID: " + lastinsertid);
...
I'm currently trying to write a txt file to a mySQL database through a Java program. My database connects correctly through a JDBC driver and I can create tables etc through the program. However when I try to read the text file in I get this error message
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''FName' , 'SName' , 'DOB') VALUES ('John' , 'McCullough' , '270696')' at line 1
I can't find an error in my SQL code. Here is the rest of the code from the class. Any help would be greatly appreciated.
try (Connection con = DriverManager.getConnection(dbUrl, dbUsername, dbPassword)) {
FileReader file1 = new FileReader("resources/Test.txt");
BufferedReader buffer1 = new BufferedReader(file1);
String read;
while ((read = buffer1.readLine()) != null) {
String[] row = read.split(",");
String fName = row[0];
String sName = row[1];
String DOB = row[2];
String insert = "INSERT INTO chessleague.table1 ('FName' , 'SName' , 'DOB') VALUES ('" + fName + "' , '" + sName + "' , '" + DOB + "')";
ps = con.prepareStatement(insert);
ps.executeUpdate();
ps.close();
}
} catch (Exception ex) {
System.out.println(ex);
}
As mentioned in the comments, don't quote the column names.
The code heavily misuses prepared statements to execute simple SQL. The Connection Class has a createStatement() method that creates a simple statement which is meant for text form SQL commands.
Statement stmt = con.createStatement();
stmt.execute("SELECT * from test.t1");
Prepared statements expect a template that is used to create the SQL statements. Here's an example of how the insert could be done with prepared statement commands.
try (PreparedStatement ps = con.prepareStatement("INSERT INTO chessleague.table1 (FName , SName , DOB) VALUES (?, ?, ?)")) {
ps.setString(0, fName);
ps.setString(1, sName);
ps.setString(2, DOB);
ps.execute();
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
}
I am trying to insert data into the database, but I am getting an error when I click the button insert.
This is the error
com.microsoft.sqlserver.jdbc.SQLServerException: There are more columns in the INSERT
statement than values specified in the VALUES clause. The number of values in the VALUES
clause must match the number of columns specified in the INSERT statement.
I would like your help if you can figure out the problem.
This is my insertion code
private void insertActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dbconnection db = new dbconnection();
try {
db.connect();
db.stm=db.con.createStatement();
java.sql.Date date1 = new java.sql.Date(jDateChooser1.getDate().getTime());
int result=db.stm.executeUpdate("insert into Blood_Test_Result" +"(DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name,Date)"
+"values('"+jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"'"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+"','"+date1+"')");
if(result>0)
{
JOptionPane.showMessageDialog(this, "Data has been saved succesfully");
}
else
{
JOptionPane.showMessageDialog(this, "no data has been saved");
}
} catch (SQLException ex) {
Logger.getLogger(BloodTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
The error is clear you are using 13 column in .
(BTRID,DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name)
But you set 12 value in values :
values(....)
So check your query step by step and make sure that you are using the correct columns.
My answer is for this important part, don't set your attributes like this, instead use PreparedStatement to avoid syntax error and SQL Injection :
String query = "insert into Blood_Test_Result" + "(BTRID, DID ,D_Name, "
+ "Weight, HBsAG, HIV, VDRL, HCV, Malaria, Blood_Type, Blood_Status, LTID,LT_Name)"
+ "values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(query)) {
insert.setString(1, jComboBox2.getSelectedItem().toString());
insert.setString(2, jTextField1.getText());
...
insert.executeUpdate();
}
The error is very clear :
You have more Columns in your statment than values!
(BTRID,DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name)
This are 13 columns and you have
jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"'"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+
only 12 values so remove colmun and it ( but the correct ;-) ) and it should work
I solved the error because i was missing a comma between two columns.
private void insertActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
dbconnection db = new dbconnection();
try {
db.connect();
db.stm=db.con.createStatement();
java.sql.Date date1 = new java.sql.Date(jDateChooser1.getDate().getTime());
int result=db.stm.executeUpdate("insert into Blood_Test_Result" +"(DID,D_Name,Weight,HBsAG,HIV,VDRL,HCV,Malaria,Blood_Type,Blood_Status,LTID,LT_Name,Date)"
+"values('"+jComboBox2.getSelectedItem().toString()+"',"
+ "'"+jTextField1.getText()+"','"+jTextField3.getText()+"','"+jComboBox4.getSelectedItem().toString()+"',"
+ "'"+jComboBox5.getSelectedItem().toString()+"','"+jComboBox6.getSelectedItem().toString()+"',"
+ "'"+jComboBox7.getSelectedItem().toString()+"','"+jComboBox8.getSelectedItem().toString()+"',"
+ "'"+jComboBox9.getSelectedItem().toString()+"','"+jComboBox10.getSelectedItem().toString()+"',"
+ "'"+jComboBox3.getSelectedItem().toString()+"','"+jTextField2.getText()+"','"+ date1 +"')");
JOptionPane.showMessageDialog(this, "insert successful");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
fill();
clear();
}
Thanks all for the help
I'm trying to figure out why this code is throwing an SQL exception. When I run this code it prints "Bad SQL in customer insert ps", which is the message in that inner catch block. I've got multiple prepared statements with SQL inserts like this both in this class and also elsewhere in my application. They're all working fine. I've looked through this one over and over again, and I can't figure out why this one is throwing an exception.
try {
Connection conn = DBconnection.getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT customerId FROM customer WHERE customerName=\"" + name + "\";");
System.out.println(ps.toString());
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customerId = rs.getString("customerId");
}
try {
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement("INSERT "
+ "INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)"
+ "VALUES(\"" + name + "\", " + addressId + ", " + active + ", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\", UTC_TIMESTAMP(), \"" + LogInController.getUserName() + "\");");
customerInsert.executeUpdate();
System.out.println(customerInsert.toString());
System.out.println(rs.toString());
} catch (SQLException sq) {
System.out.println("Bad SQL in customer insert ps");
}
} catch (SQLException customerIdException) {
System.out.println("Bad SQL in customer ps");
}
You're using PreparedStatement as though you were using Statement. Don't put the parameters in the SQL, put in placeholder ? marks. Then use the various setXyz methods (setString, setInt, etc.) to fill in the parameters:
PreparedStatement customerInsert = DBconnection.getConnection().prepareStatement(
"INSERT INTO customer (customerName, addressId, active, createDate, createdBy, lastUpdate, lastUpdateBy)" +
"VALUES(?, ?, ?, ?, ?, ?, ?);"
);
customerInsert.setString(1, name);
customerInsert.setInt(2, addressId);
// ...etc. Notice that the parameter indexes start with 1 rather than 0 as you might expect
I get syntax error to mysql insert statement. May I know how to correct this error ?
user=txtuser.getText();
char[] pass=jPasswordField1.getPassword();
String passString=new String(pass);
try{
Connection con = createConnection();
Statement st = con.createStatement();
**String sql = "INSERT INTO login(username,Password)"+"VALUES"+"('"user"','"passString"')";**
st.executeUpdate(sql);
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Exception: "+ e.toString());
}
You're missing a few + operators:
String sql = "INSERT INTO login(username,Password) VALUES ('" + user + "','" + passString + "')";
Consider using PreparedStatement placeholders to set these parameters. This will protect you from SQL injection attacks also. Here is an example