SQL(Java,h2):检索刚插入数据库的单个项的唯一ID的最佳方法是什么? [英] SQL (Java, h2): What's the best way to retrieve the unique ID of the single item I just inserted into my database?
本文介绍了SQL(Java,h2):检索刚插入数据库的单个项的唯一ID的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我目前的方法是这样的:
My current method is this:
SELECT TOP 1 ID FROM DATAENTRY ORDER BY ID DESC
这假定最新插入的项目始终具有最高的唯一ID(主键,自动增量)。这里有点气味。
This assumes the latest inserted item always has the highest unique ID (primary key, autoincrementing). Something smells wrong here.
替代品?
推荐答案
如果JDBC驱动程序支持它,你也可以只使用 声明#getGeneratedKeys()
。
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?
}
这篇关于SQL(Java,h2):检索刚插入数据库的单个项的唯一ID的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文