SQL(Java,h2):检索我刚刚插入数据库的单个项目的唯一 ID 的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2647407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:11:21  来源:igfitidea点击:

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

javasqljdbch2unique-id

提问by Daddy Warbox

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.

这假设最新插入的项目始终具有最高的唯一 ID(主键,自动递增)。这里有些不对劲。

Alternatives?

备择方案?

回答by BalusC

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

如果 JDBC 驱动程序支持它,您也可以使用Statement#getGeneratedKeys()它。

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

回答by Sean

If using MySQL you can do

如果使用 MySQL,你可以做

select last_insert_id();

If using MS SQL

如果使用 MS SQL

select scope_identity();

For H2, I believe it's

对于 H2,我相信是

CALL SCOPE_IDENTITY();

but I don't have any experience with that DB

但我对那个数据库没有任何经验