Here is an example.
- String insertSQL=
- "INSERT INTO client_info(client_id,first_name,update_time) values (client_id.nextval,?,systimestamp)";
- int[] keys={1};
- // retrieve connection
- PreparedStatement stmt=cn.prepareStatement(insertSQL,keys);
- int cnt = stmt.executeUpdate();
- ResultSet rs = stmt.getGeneratedKeys();
- rs.next();
- clientIdKey=rs.getInt(1);
In line 3 an int array is created to specify the column index of the auto generated key in the Insert SQL. In line 5 you pass the array created in line 3 as second argument to prepareStatement call. Once the query is executed you call getGeneratedKeys() method on the prepared statement object to retrieve the result set and then access this resultset to retrieve the generated keys.
This feature is supported from Oracle 10g R2 JDBC Drivers, not in previous JDBC versions (though this driver can be used for Oracle 9i as well). The ROWID is the default generated key retuned.