You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复Java中的java.lang.ArrayIndexOutOfBoundsException: 4 >= 4错误?

问题分析与修复方案

嘿,这个ArrayIndexOutOfBoundsException: 4 >= 4错误其实很好定位,咱们一步步拆解问题并修复:

1. 表格列索引越界的直接原因

先看你添加表格行的代码:

model.addRow(new Object[] {
    ((JTextField) invo_date.getDateEditor().getUiComponent()).getText(), 
    ((JTextField) invo_date1.getDateEditor().getUiComponent()).getText(), 
    dec.getText(), 
    BL.getText()
});

这里你只给表格行添加了4个数据元素,对应表格的列索引是0、1、2、3(总共4列)。但在后续循环存数据的时候,你却尝试获取第5列(索引为4)的值:

String container = (String) jTable2.getValueAt(row, 4);

这就直接触发了数组越界——表格根本没有第5列,自然拿不到数据。

修复方式二选一:

  • 如果你的业务确实需要container这列数据,那添加行的时候就要把它补进去,比如:
model.addRow(new Object[] {
    ((JTextField) invo_date.getDateEditor().getUiComponent()).getText(), 
    ((JTextField) invo_date1.getDateEditor().getUiComponent()).getText(), 
    dec.getText(), 
    BL.getText(),
    containerInput.getText() // 替换成你实际的container输入框对象
});
  • 如果不需要这列数据,直接删除代码中String container = ...这一行,以及后面的pst.setString(5, container);。

2. SQL语句的语法错误

你的SQL写了个低级错误:update into是不存在的语法,插入数据应该用insert into:

// 错误写法
String queryco = "update into status(date, to_date, description, containers) values( ?,?,?,?)";
// 正确写法
String queryco = "insert into status(date, to_date, description, containers) values( ?,?,?,?)";

要是你本意是更新数据,那应该用update status set ... where ...,但从逻辑看你是批量插入表格数据,所以用insert into才对。


3. PreparedStatement参数不匹配

你的SQL语句里只有4个占位符( ?,?,?,?),但代码里却设置了5个参数:

pst.setString(1, datee);
pst.setString(2, mpakadates);
pst.setString(3, descri);
pst.setString(4, total);
pst.setString(5, container); // 这个参数在SQL里找不到对应的占位符

这会导致后续执行时抛出SQL语法错误,修复方式和第一点对应:要么在SQL的字段列表里添加container字段,要么删除这个多余的参数设置。


4. 其他细节优化

  • 执行批量操作后不需要再调用pst.execute(),pst.executeBatch()已经能完成批量插入,重复调用反而可能出问题。
  • 代码里的st.close()是无效的,因为你根本没定义st这个变量,直接删掉这行就行。
  • 建议用try-with-resources语法自动关闭数据库连接和PreparedStatement,避免资源泄漏:
try (Connection conn = JavaDb.ConnectDB();
     PreparedStatement pst = conn.prepareStatement(queryco)) {
    int rows = jTable2.getRowCount();
    for (int row = 0; row < rows; row++) {
        // 这里写获取表格数据、设置参数的逻辑
        pst.addBatch();
    }
    pst.executeBatch();
    JOptionPane.showMessageDialog(this, "Data Saved Successfully");
} catch (Exception e) {
    System.err.println("Got an exception! " + e);
    System.err.println(e.getMessage());
}

内容的提问来源于stack exchange,提问作者Arbaaz Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:58:32