NashPL
NashPL

Reputation: 481

Java JDBC Return wrong generated keys

I am trying to get an ID of a newly inserted row from my database. After debugging and following the code step by step but it always returns a "0" value.

HashMap<String, String> response = new HashMap<String, String>();
    Integer generatedId = 0;
    try {
        ps = con.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
        ps.executeUpdate();
        rs = ps.getGeneratedKeys();
        rs.next();
        if (rs.isBeforeFirst()) {
            generatedId = rs.getInt(1);
        }
    } catch (SQLException e) {
        System.out.println(e.getMessage());
        response.put("STATUS", "ERROR");
    }

The code sits in a static method called update which accepts a string with SQL query String.

public static HashMap<String, String> update(String query)

Upvotes: 0

Views: 109

Answers (1)

user207421
user207421

Reputation: 310883

Your code makes no sense.

If you call rs.next(), as you should, rs.isBeforeFirst() cannot possibly be true, and the following rs.getInt() would fail if it was.

Remove the test. It should really be if (rs.next()) etc.

Upvotes: 1

Related Questions