我正在尝试将Jtable中的所有数据添加到mysql数据库中。但数据添加成功。但是数据两次添加到数据库中。我附上数据库表下面的屏幕截图,如何添加记录
enter image description here

这是我尝试过的代码

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());
}

最佳答案

就像在您的代码中一样,您要一步一步地遍历每一行,并且在每次迭代时都要执行这两项:

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


这就是为什么同一行被插入两次的原因。
您可以采用以下解决方案来避免多次插入。


仅在循环中使用preparedStmt.executeUpdate();并删除preparedStmt.executeBatch();

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

不要使用preparedStmt.executeUpdate();并将preparedStmt.executeBatch();移到循环外。

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

10-04 10:22
查看更多