2016-05-05 14 views
1

ojdbcを使用して挿入後に自動生成IDを取得しようとしています。OJDBCで生成されたIDを取得するにはどうすればよいですか?

私のコードは次のようである:私はjava.lang.ArrayIndexOutOfBoundExceptionを取得しています

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); 
    } 
} 

:8

答えて

0

は、以下のようにあなたのPreparedStatementを変更してみてください。私は配列のすべての列をリストし、引数としてprepareStatementに渡す必要があると思います。 ArrayIndexOutOfBoundExceptionが修正される可能性があります。

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

1)オプション。 stmt = con.prepareStatement(query, String[]{ID_COLUMN_NAME});

2)オプション 動作する必要がありますが、テストしていません。 getReturnResultSet() - DMLから返されたデータを含む結果セットを返します。

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, ?, ?, ?, ?, ?, ?, ?, ?) returning ID into ?  "; 
    PreparedStatement stmt = null; 
    try { 
     stmt = con.prepareStatement(query); 
     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.registerReturnParameter(9, OracleTypes.INTEGER); 
     stmt.executeUpdate(); 
     ResultSet idResults = ((OraclePreparedStatement stmt).getReturnResultSet(); 
     if(null != idResults && idResults.next()){ 
      id = idResults.getInt(9); 
     } 
    } finally { 
     cleanupConnection(con, stmt, null); 
    } 
} 
関連する問題