SQL (Java, h2): What's the best way to retrieve the unique ID of the single item I just inserted into my database?

Daddy Warbox picture Daddy Warbox · Apr 15, 2010 · Viewed 13.3k times · Source

My current method is this:

SELECT TOP 1 ID FROM DATAENTRY ORDER BY ID DESC

This assumes the latest inserted item always has the highest unique ID (primary key, autoincrementing). Something smells wrong here.

Alternatives?

Answer

BalusC picture BalusC · Apr 15, 2010

If the JDBC driver supports it, you can also just use Statement#getGeneratedKeys() for that.

String sql = "INSERT INTO tbl (col) VALUES (?)";
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, col);
preparedStatement.executeUpdate();
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
    long id = generatedKeys.getLong(1);
} else {
    // Throw exception?
}