Search code examples
javajdbcderby

getGeneratedKeys() returns an Empty ResultSet


Hello there and thanks for reading. I'm trying to retrieve the ID of the newly inserted data, but I always get an empty ResultSet.

 Connection con = main.getCon();
 String sqlCommand = "Insert Into Relations(name,explanation) values(?,?)";
 PreparedStatement state = 
 con.prepareStatement(sqlCommand,Statement.RETURN_GENERATED_KEYS);
 state.setString(1,name.getText());
 state.setString(2,explanation.getText());
 int affectedRows = state.executeUpdate();
 assert (affectedRows>0);
        
 ResultSet rs = state.getGeneratedKeys();
 assert rs.next();
 int instertedID= rs.getInt("ID");

Not sure what's wrong with it. Checked different samples online, but couldn't figure out what's my mistake. I also tried it with Statement, but no luck with that either.
Point 1: the code runs smoothly and my data in inserted into the database. Point 2: there are examples online for this very case, you can check it here: https://www.baeldung.com/jdbc-returning-generated-keys

I just realized that my ResultSet wasn't empty, I had problem with using my debugger and that's why I thought it was empty. As Mark Rotteveel mentioned in a comment, the problem was with "assert" statement.


Solution

  • The problem is your use of assert rs.next(). Assertions in Java are intended for checking invariants (eg during testing), but when you normally run Java, assert statements are not executed, they are only executed when explicitly enabling this with the -ea commandline option.

    As a result, rs.next() is not called, so your result set is still positioned before the first row when you call rs.getInt(1). Instead use if (rs.next()) { ... }.