首页 > 解决方案 > 使用 JTable java 在数据库中添加了两次数据

问题描述

我正在尝试将 Jtable 中的所有数据添加到 mysql 数据库中。但数据添加成功。但数据两次添加到数据库中。我附上了下面的数据库表屏幕截图如何添加记录 在此处输入图像描述

这是我尝试过的代码

try{      

  int rows=jTable1.getRowCount();
  Class.forName("com.mysql.jdbc.Driver");   
  java.sql.Connection  con1=DriverManager.getConnection("jdbc:mysql://localhost/javasales","root",""); 
  con1.setAutoCommit(false);
  String queryco = "Insert into sales_product(product,price) values (?,?)";    
  PreparedStatement preparedStmt = (PreparedStatement) con1.prepareStatement(queryco,Statement.RETURN_GENERATED_KEYS);
  for(int row = 0; row<rows; row++)
  {         
    String product = (String)jTable1.getValueAt(row, 0);
    String price = (String)jTable1.getValueAt(row, 1);       
    preparedStmt.setString(1, product);
    preparedStmt.setString(2, price);
    preparedStmt.executeUpdate();
    ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
     preparedStmt.addBatch();

    preparedStmt.executeBatch();
    con1.commit();       
  }
  JOptionPane.showMessageDialog(null, "Successfully Save");    
}
catch(ClassNotFoundException | SQLException | HeadlessException e){
  JOptionPane.showMessageDialog(this,e.getMessage());
}

标签: javamysqljdbc

解决方案


与您的代码一样,您将逐行迭代每一行,并且在每次迭代中您都在执行两者:

preparedStmt.executeUpdate();
preparedStmt.executeBatch();

这就是为什么同一行被插入了两次。您可以使用以下解决方案以避免多次插入。

  1. preparedStmt.executeUpdate();在循环内使用并删除 preparedStmt.executeBatch();

    preparedStmt.executeUpdate();
        ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
    //     preparedStmt.addBatch();
      //  preparedStmt.executeBatch();
        con1.commit();       
      }
    
  2. 不要使用preparedStmt.executeUpdate();和移动preparedStmt.executeBatch();到循环之外。

    //preparedStmt.executeUpdate();
    //ResultSet generatedKeyResult = preparedStmt.getGeneratedKeys();
     preparedStmt.addBatch();
    }
    preparedStmt.executeBatch();
    con1.commit();
    

推荐阅读