Skip to content
accelerando

JDBC: Autogenerated keys revisited.

Some months ago i wrote about retrieving auto generated values with JDBC from an Oracle Database: JDBC: Get autogenerated keys on a Oracle DB.

The solution i presented in the previous article doesn’t run in a Oracle Java Stored Procedure.

To accomplish this, use a callable statement like this:

final String sql = "BEGIN INSERT INTO foobar(id, b) VALUES (id.nextval, ?) RETURNING id INTO ?; END;";
CallableStatement cs = connection.prepareCall(sql);
stmt.setString(1, "bar");
stmt.registerOutParameter(2, Types.INTEGER);
stmt.executeUpdate();		
rv = rs.getInt(2);

This way you get the id generated by the sequence id without first selecting and then using it.

Post a Comment

Your email is never published nor shared. Required fields are marked *
*
*

*