设置预准备语句时获取ArrayIndexOutOfBoundsException

时间:2015-08-20 02:47:28

标签: java

我在设置sql

的参数时遇到异常
java.ljava.lang.ArrayIndexOutOfBoundsException: 8
at oracle.jdbc.driver.OracleSql.computeBasicInfo(OracleSql.java:950)
    at oracle.jdbc.driver.OracleSql.getSqlKind(OracleSql.java:623)
    at oracle.jdbc.driver.OraclePreparedStatement.(OraclePreparedStatement.java:1212)
    at oracle.jdbc.driver.T4CPreparedStatement.(T4CPreparedStatement.java:28)
    at oracle.jdbc.driver.T4CDriverExtension.allocatePreparedStatement(T4CDriverExtension.java:68)
    at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3140)
    at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:3042)
    at oracle.jdbc.driver.PhysicalConnection.prepareStatement(PhysicalConnection.java:5890)

代码:

String sql = "insert into TEST_TABLE1(Field1,Field2,Field3,Field4,Field5,Field6,Field7,Field8,Field9,Field10) values(?,?,?,?,?,?,?,?,?,TEST_SEQ.nextval)";

protected static PreparedStatement prepareStatement(Connection connection , String sql , String idName, Object... values) throws SQLException{

    PreparedStatement statement = connection.prepareStatement(sql, new String[] {idName});

    setValues(statement, values);
    return statement;
}

protected static void setValues (PreparedStatement statement , Object... values) throws SQLException{
    for( int i = 0; i < values.length;i++){
        statement.setObject(i+1,values[i]);
    }
}

public long create (Connection connection, String sql, String idName, Object... parameters) throws ClassNotFoundException , SQLException{

    long key = -1;
    PreparedStatement statement = null;
    ResultSet resultset = null;

    try{
        statement = prepareStatement(connection,sql,idName,parameters);
        logger.debug("prepareStatement created");

        statement.execute();
        resultset = statement.getGeneratedKeys();

        if(resultset != null && resultset.next()){
            key = resultset.getLong(1)
        }
        logger.debug("key :"+key);

    }catch(SQLException sqle){
        logger.debug("error while creating db :"+slqe);
        throw sqle;
    } finally{
        close(statement,resultset);
    }
    return key;
}

1 个答案:

答案 0 :(得分:2)

Refer to "JDBC - Oracle ArrayIndexOutOfBoundsException"

ArrayIndexOutOfBoundsException when use AutoGeneratedKeys and Oracle

我有类似的问题最终在做

  

1&gt;在调用create之前获取序列值(方法参数...)   long sequnceVal = getSequence(String sequenceSql);

2&gt;将prepareStatement更改为

    protected static PreparedStatement prepareStatement(Connection connection,
        String sql, String idName, Object... values)
        throws SQLException {

    PreparedStatement statement = connection.prepareStatement(sql);

    setValues(statement, values);
    return statement;
}