Unable to find a generated key in Java using PreparedStatement's getGeneratedKeys() Unable to find a generated key in Java using PreparedStatement's getGeneratedKeys() oracle oracle

Unable to find a generated key in Java using PreparedStatement's getGeneratedKeys()


I expect that the "key" you're getting back that looks like a string is the ROWID-- that's the only key that the database is directly generating. You should be able to change that to get your id column back (this probably requires a moderately recent version of the JDBC driver).

//initiate connection, statement etcString generatedColumns[] = {"ID"};pStatement = connection.prepareStatement(SQL, generatedColumns);pStatement.setString(1,'blabla');pStatement.executeUpdate();ResultSet rs = pStatement.getGeneratedKeys();while (rs.next()){  //debugging here to see what rs has}

You could also change your query to explicitly add the RETURNING clause

String SQL = "insert into table (id, name) " +              "  values (sequence.nextval, ?) " +              "  returning id into ?";


If this is not working, the problem could be with sequence.nextval. It seems like if you're using that, you are not technically autogenerating the key


I'm pretty sure that getGeneratedKeys won't return the value of a key that was initialized with the next value of a sequence. Indeed, in this case, the database doesn't generate the key by itself (like it would with an auto-increment column).

If you want to know the generated key, then execute a first query:

select sequence.nextval from dual

and then use the result of this first query to execute your prepared statement:

insert into table (id, name) values (?, ?)