使用 Java 中的 sqlite 获取最后插入的 id 的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/216790/
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
What's the best way to get the last inserted id using sqlite from Java?
提问by Ross
What's the best way to get the last inserted id using sqlite from Java? Google is giving me different answers--some say select the last-insert-rowid; others say call statement.getGeneratedKeys(). What's the best route to take? (I just want to return the id, not use it for other inserts or anything.)
使用 Java 中的 sqlite 获取最后插入的 id 的最佳方法是什么?谷歌给了我不同的答案——有人说选择最后一个插入行;其他人说调用 statement.getGeneratedKeys()。最好的路线是什么?(我只想返回 id,而不是将它用于其他插入或任何内容。)
采纳答案by Brian
Use getGeneratedKeys()
if your JDBC driver supports it. You don't want to muck around trying to get the key yourself after the insert. If your driver does not support getGeneratedKeys()
then I would get the next value from the key before the insert.
getGeneratedKeys()
如果您的 JDBC 驱动程序支持它,请使用它。您不想在插入后尝试自己获取密钥。如果您的驱动程序不支持,getGeneratedKeys()
那么我会在插入之前从键中获取下一个值。
回答by David Citron
Either approach executes the same exact SQL statement, but java.sql.Statement.getGeneratedKeys()
is more portable to different underlying databases.
这两种方法都执行完全相同的 SQL 语句,但java.sql.Statement.getGeneratedKeys()
对不同的底层数据库更具可移植性。
Using either the sqlite3_last_insert_rowid()
C API function or the last_insert_rowid()
SQL function is the correct way to retrieve the rowid generated during the last insert.
使用sqlite3_last_insert_rowid()
C API 函数或last_insert_rowid()
SQL 函数是检索上次插入期间生成的 rowid 的正确方法。
SQLite supports the SQL scalar functionsyntax as:
SQLite 支持SQL 标量函数语法为:
SELECT function-name();
Therefore, if you do not have access to the C API directly, you can invoke the scalar function last_insert_rowid()
via a SELECT
statement.
因此,如果您无法直接访问 C API,则可以last_insert_rowid()
通过SELECT
语句调用标量函数。
If you look at the source codefor the SQLiteJDBCimplementation (is this what you're using?) you will see that this is exactly what the author of that JDBC wrapper has done:
如果你看一下源代码的SQLiteJDBC实现(这是你用什么?)你会看到,这是JDBC的作者正是包装做:
ResultSet getGeneratedKeys() throws SQLException {
if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement(
"select last_insert_rowid();");
return getGeneratedKeys.executeQuery();
}