2

I'm blocked on a stupid problem in one of my functions. I want to get the generatedKey of one of my Sql query. I can't and i don't understand why. The problem is that resultSet.next() it return false even if the line have been inserted when I check the data in the table.

Here is my code :

Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');");

 ResultSet resultSet = statement.getGeneratedKeys();
 resultSet.next();

Solution : Add Statement.RETURN_GENERATED_KEYS

Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO calamar.calamar.application (nom,criticite,autorise) VALUES ('"+nom+"','"+criticite+"','"+false+"');", Statement.RETURN_GENERATED_KEYS);

ResultSet resultSet = statement.getGeneratedKeys();
resultSet.next();
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Antoine Grenard
  • 1,712
  • 3
  • 21
  • 41
  • 2
    Try adding `Statement.RETURN_GENERATED_KEYS` as the second argument to the `.executeUpdate` method call (after the SQL statement). – Gord Thompson Apr 24 '16 at 20:24
  • oh my god ... It worked thank you so much ! – Antoine Grenard Apr 24 '16 at 20:35
  • 1
    You should post your solution as an answer and even accept it. – Luc M Apr 24 '16 at 20:39
  • 1
    I'm surprised that this works. `INSERT INTO calamar.calamar.application` is invalid for Postgres because you can't have a three part identifier there. Are you _sure_ you are using Postgres? Also: please use a `PreparedStatement` instead http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html –  Apr 24 '16 at 20:46
  • I'm pretty sure i'm using it and that it works. Isn't i should do : db.schema.table ? – Antoine Grenard Apr 24 '16 at 21:18
  • 1
    Possible duplicate of [How to get the insert ID in JDBC?](http://stackoverflow.com/questions/1915166/how-to-get-the-insert-id-in-jdbc) – Mark Rotteveel Apr 25 '16 at 07:37

0 Answers0