Could not find generated key in Java using PreparedStatement getGeneratedKeys ()

I have a request:

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

Then I create the PreparedStatement as follows:

//initiate connection, statement etc
pStatement = connection.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
pStatement.setString(1,'blabla');

pStatement.executeUpdate();
ResultSet rs = pStatement.getGeneratedKeys();

while (rs.next()){
  //debugging here to see what rs has
}

When executing and debugging at this point of debugging, I see that the ResultSet has only one key, the string is not the same as the id that I expect at all. When checking the database, everything works fine, the identifier is inserted and that’s it. Something about getGeneratedKeys (); what bothers me.

What am I doing wrong?

Thanks in advance

+5
source share
5 answers

, "", , , - ROWID - , . , id (, , JDBC).

//initiate connection, statement etc
String 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
}

, RETURNING

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

, .nextval. , ,

+1

, getGeneratedKeys , . , (, ).

, :

select sequence.nextval from dual

:

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

:

pStatement.setString('blabla');

:

pStatement.setString(1, 'blabla');

, .

+1

: PreparedStatement, RETURN_GENERATED_KEYS:

pStatement = connection.prepareStatement(SQL, PreparedStatement.RETURN_GENERATED_KEYS);

getGeneratedKeys() , , ResultSet.

, - ( Justin, ). , , :

id = rs.getInt("id_row_name");

:

id = rs.getInt(column_number); //One column for each key retrieved.
0

All Articles