I'm trying to update my database with java. I'm working in Netbeans, there is no error in the code but still, the rows are not updated.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(ClassNotFoundException | InstantiationException | IllegalAccessException e){
JOptionPane.showMessageDialog(this,"Error in connectivity" );
}
try{
String m11 = jTextField1.getText();
String m22 = jTextField2.getText();
com.mysql.jdbc.Connection conn = (com.mysql.jdbc.Connection)DriverManager.getConnection("jdbc:mysql://localhost/inventorysystem","root","root123");
Statement stmt = conn.createStatement();
int bp = JOptionPane.showConfirmDialog(this,"Do you want to update the record ?");
if(bp == JOptionPane.YES_OPTION){
String query = "update inventorycatalogmap set inventorycatalogname = '"+m11+"' and ProductCatalog='"+m22+"' where inventorycatalogname='"+m11+"';";
stmt.execute(query);
JOptionPane.showMessageDialog(this,"Record has been updated");
}
if(bp == JOptionPane.CANCEL_OPTION){
NewFrame2 t = new NewFrame2();
t.dispose();
t.setVisible(true);
}
if(bp == JOptionPane.NO_OPTION){
NewFrame2 i = new NewFrame2();
i.dispose();
i.setVisible(true);
}
stmt.close();
conn.close();
}
catch(SQLException | HeadlessException e){
JOptionPane.showMessageDialog(null,"Invalid Entry","message",2);
}
}
Can anyone suggest, what went wrong in my implementation?
You are missing conn.commit();
stmt.close();
conn.commit();
conn.close();
And probably your connection's auto-commit is not set true.
Your code is open to syntax error and SQL Injection instead you have to use PreparedStatement
it is more secure and more helpful :
String query = "update inventorycatalogmap set inventorycatalogname = ?, ProductCatalog=? where inventorycatalogname=?";
try (PreparedStatement update = conn.prepareStatement(query)) {
update.setString(1, m11);
update.setString(2, m22);
update.setString(3, m11);
update.executeUpdate();
}
You have an error in your query :
set inventorycatalogname = '" + m11 + "' and ProductCatalog='" + m22 + "' where
//---------------------------------------^^^
Also you should not use and
when you set many fields you have to separate them just with ,
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.