如何将JTable数据存入MySQL?解决ArrayIndexOutOfBoundsException异常
解决JTable存MySQL时的ArrayIndexOutOfBoundsException问题
嘿,这个异常我太熟悉了,本质就是JTable的行索引越界了,咱们一步步拆解问题和解决方案:
异常根源
你看到的Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 2 >= 2,核心原因很简单:
JTable的行索引是从0开始计数的,但你用getRowCount()拿到的是表格的总行数。举个例子:如果表格有2行,有效行索引只有0和1,但你直接把总行数2作为索引去调用getValueAt(),肯定会超出范围触发异常。
看你的代码就能直接找到问题点:
int fila2 = this.rSTableMetro4.getRowCount(); int fila3 = this.rSTableMetro3.getRowCount(); int fila5 = this.rSTableMetro5.getRowCount(); int fila4 = this.td7.getRowCount();
这些变量都是直接用总行数当行索引,比如td7.getRowCount()如果返回2,你调用td7.getValueAt(fila4,2)就是用索引2去访问只有0、1两行的表格,直接触发2 >= 2的越界异常。
修复步骤
1. 修正行索引取值
如果你是想获取表格最后一行的数据,把所有getRowCount()的结果减1,得到最后一行的有效索引:
// 修正行索引,取最后一行的有效索引 int fila2 = this.rSTableMetro4.getRowCount() - 1; int fila3 = this.rSTableMetro3.getRowCount() - 1; int fila5 = this.rSTableMetro5.getRowCount() - 1; int fila4 = this.td7.getRowCount() - 1;
2. 增加空表格判断
如果表格是空的(getRowCount()返回0),减1后会得到-1,还是会触发异常。所以在取值前要先判断表格是否有数据:
try { PreparedStatement pst = (PreparedStatement) registro.prepareStatement(sql); // 处理rSTableMetro2(注意你代码里的fila变量也要确认是有效索引) if (fila >= 0) { pst.setString(1, this.rSTableMetro2.getValueAt(fila, 0).toString()); } else { pst.setString(1, ""); // 或者设为null,根据你的数据库字段要求调整 } // 处理rSTableMetro4 if (fila2 >= 0) { pst.setString(2, this.rSTableMetro4.getValueAt(fila2, 0).toString()); } else { pst.setString(2, ""); } // 同理处理rSTableMetro3、rSTableMetro5 if (fila3 >= 0) { pst.setString(3, this.rSTableMetro3.getValueAt(fila3, 0).toString()); } else { pst.setString(3, ""); } if (fila5 >= 0) { pst.setString(4, this.rSTableMetro5.getValueAt(fila5, 0).toString()); } else { pst.setString(4, ""); } // 处理td7的三个字段 if (fila4 >= 0) { pst.setString(5, this.td7.getValueAt(fila4,0).toString()); pst.setString(6, this.td7.getValueAt(fila4,1).toString()); pst.setString(7, this.td7.getValueAt(fila4,2).toString()); } else { pst.setString(5, ""); pst.setString(6, ""); pst.setString(7, ""); } // 执行插入操作 pst.executeUpdate(); // 别忘了关闭资源,避免内存泄漏 pst.close(); registro.close(); } catch (SQLException e) { e.printStackTrace(); }
3. 确认fila变量的有效性
你代码里用到的fila变量没有给出定义,也要确保它的取值在0到rSTableMetro2.getRowCount()-1之间,避免同样的越界问题。
额外优化建议
数据库操作最好用try-with-resources语法自动关闭资源,比手动关闭更安全,能避免遗漏:
try (Connection registro = cnx.connect(); PreparedStatement pst = registro.prepareStatement(sql)) { // 这里写赋值和执行代码 } catch (SQLException e) { e.printStackTrace(); }
内容的提问来源于stack exchange,提问作者Edx
相关产品推荐
相关产品推荐

