繁体   English   中英

我正在尝试使用java更新数据库。 我在netbeans中工作,代码中没有错误,但行仍未更新

[英]I'm trying to update my database with java . i'm working in netbeans , there no error in the code but still the rows are not updated

我正在尝试使用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); 
          }
        }   

任何人都可以建议,我的实现中出了什么问题?

您缺少conn.commit();

stmt.close();
 conn.commit();
 conn.close();

可能您的连接的自动提交未设置为true。

您的代码易于出现语法错误和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当您设置许多字段时,只需将它们分开即可,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM