我试图用java更新我的数据库。我在Netbeans工作,代码中没有错误但仍然没有更新行。
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);
}
}
有人可以建议,我的实施出了什么问题?
答案 0 :(得分:0)
你缺少conn.commit();
stmt.close();
conn.commit();
conn.close();
可能你的连接的自动提交没有设置为真。
答案 1 :(得分:0)
你的代码是开放的语法错误和SQL注入,而你必须使用PreparedStatement
它更安全,更有帮助:
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();
}
您的查询中有错误:
set inventorycatalogname = '" + m11 + "' and ProductCatalog='" + m22 + "' where
//---------------------------------------^^^
另外,当您设置许多字段时,不应使用and
,只需使用,