如何解决JTable多行数据插入MySQL数据库时仅首行生效的问题
问题原因
- 核心错误是你把
tblmodel.setRowCount(0)写在了for循环内部,第一次插入完首行数据后就直接清空了JTable的所有行,此时循环判断条件i<tblmodel.getRowCount()里的行计数已经变为0,循环直接终止,剩下的行自然不会被插入。 - 额外存在的不合理逻辑:你没有处理抛出的异常,即使后续插入出错也不会有任何提示,很难定位问题;同时每次循环都重复创建PreparedStatement、每次插入完都弹提示框的设计也不符合使用逻辑。
修正后代码
DefaultTableModel tblmodel= (DefaultTableModel) jTable1.getModel(); // 提前缓存行计数,避免循环过程中表格内容变化影响判断 int rowCount = tblmodel.getRowCount(); if (rowCount == 0) { JOptionPane.showMessageDialog(this, "Table is Empty"); } else { Connection con = null; PreparedStatement ps = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","123456"); // 把PreparedStatement创建放在循环外,复用预编译逻辑提升性能 String query = "Insert into invoice(product_id, product_name, price,quantity, total_price) values (?,?,?,?,?)"; ps = con.prepareStatement(query); for (int i=0; i<rowCount; i++) { String pid = (String)jTable1.getValueAt(i, 0); String pname = (String)jTable1.getValueAt(i, 1); int price = (int)jTable1.getValueAt(i, 2); int qty = (int)jTable1.getValueAt(i, 3); int tprice = (int)jTable1.getValueAt(i, 4); ps.setString(1, pid); ps.setString(2, pname); ps.setInt(3, price); ps.setInt(4, qty); ps.setInt(5, tprice); ps.execute(); } // 所有行插入成功后再弹提示、清空表格 JOptionPane.showMessageDialog(this , "所有数据添加成功"); tblmodel.setRowCount(0); } catch (Exception e) { // 不要吞异常,打印错误信息方便排查 JOptionPane.showMessageDialog(this, "数据插入失败:" + e.getMessage()); e.printStackTrace(); } finally { // 关闭数据库资源避免连接泄漏 try { if(ps != null) ps.close(); if(con != null) con.close(); } catch (Exception e) { e.printStackTrace(); } } }
内容的提问来源于stack exchange,提问作者Joshua Mathew
相关产品推荐
相关产品推荐

