java - 使用 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());
}
解决方案
与您的代码一样,您将逐行迭代每一行,并且在每次迭代中您都在执行两者:
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();
推荐阅读
- arrays - 如何在不使用任何循环的情况下编写此代码
- macos - macOS 命令行实用程序与 CoreBluetooth 权限 (iTerm)
- mongodb - Mongodb 聚合 - 最小值但不为零
- java - 从 Java 中的 Pair 键形成不同的字符串
- javascript - fullcalender 一周的最后一天的宽度错误
- nosql - DynamoDb 多对多更新复制数据
- javascript - 未找到 Webpack 构建模块查看源路径
- css - 如何制作子导航栏两到三列
- angular - 为什么第一次渲染时我的组件中的对象对象闪烁,(Angular)
- flutter - Flutter Hot Reload 不适用于模拟器。如何删除开发工具?