我正在尝试使用ojdbc插入后获取自动生成的ID。

我的代码是这样的:

public void insert(Connection con) throws SQLException {
    String query = "INSERT INTO MY_TABLE (ID, FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6, FIELD7, FIELD8) VALUES (SEQ_MY_TABLE_ID.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?)";
    PreparedStatement stmt = null;
    try {
        stmt = con.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
        stmt.setBigDecimal(1, null == field1 ? null : new BigDecimal(field1));
        stmt.setBigDecimal(2, null == field2 ? null : new BigDecimal(field2));
        stmt.setBigDecimal(3, field3);
        stmt.setString(4, field4);
        stmt.setBigDecimal(5, field5);
        stmt.setBigDecimal(6, null == field6 ? null : new BigDecimal(field6));
        stmt.setBigDecimal(7, null == field7 ? null : new BigDecimal(field7));
        stmt.setString(8, field8);
        stmt.executeUpdate();
        ResultSet idResults = stmt.getGeneratedKeys();
        if(null != idResults && idResults.next()){
            id = null == idResults.getBigDecimal(ID_COLUMN_NAME) ? null : idResults .getBigDecimal(ID_COLUMN_NAME).toBigInteger();
            //do something with the id we get back from the database
        }
    } finally {
        cleanupConnection(con, stmt, null);
    }
}


我正在获取java.lang.ArrayIndexOutOfBoundException:8

最佳答案

尝试如下更改您的PreparedStatement。我认为您需要列出数组中的所有列,并将其作为参数传递给prepareStatement。那可能会修复ArrayIndexOutOfBoundException。

stmt = con.prepareStatement(query, new String[] {"ID","FIELD1","FIELD2","FIELD3","FIELD4","FIELD5","FIELD6","FIELD7","FIELD8"});

10-06 05:11