开发者

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

This question already has answers here: How to get the insert ID in JDBC? (14 answers) 开发者_开发技巧 Closed 7 years ago.

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?


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?
}


If using MySQL you can do

select last_insert_id();

If using MS SQL

select scope_identity();

For H2, I believe it's

CALL SCOPE_IDENTITY();

but I don't have any experience with that DB

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜