14

使用 Java 中的 sqlite 获取最后插入的 id 的最佳方法是什么?谷歌给了我不同的答案——有人说选择last-insert-rowid;其他人说调用 statement.getGeneratedKeys()。最好的路线是什么?(我只想返回 id,而不是将其用于其他插入或任何东西。)

4

2 回答 2

23

两种方法都执行完全相同的 SQL 语句,但java.sql.Statement.getGeneratedKeys()更易于移植到不同的底层数据库。

使用sqlite3_last_insert_rowid()C API 函数或last_insert_rowid()SQL 函数是检索上次插入期间生成的 rowid 的正确方法。

SQLite 支持SQL 标量函数语法:

SELECT function-name();

因此,如果您无法直接访问 C API,则可以last_insert_rowid()通过SELECT语句调用标量函数。

如果您查看SQLiteJDBC实现的源代码(这是您正在使用的吗?),您会发现这正是 JDBC 包装器的作者所做的:

ResultSet getGeneratedKeys() throws SQLException {
    if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement(
        "select last_insert_rowid();");
    return getGeneratedKeys.executeQuery();
}
于 2009-03-07T14:20:51.877 回答
11

getGeneratedKeys()如果您的 JDBC 驱动程序支持,请使用它。您不想在插入后自己尝试获取密钥。如果您的驱动程序不支持getGeneratedKeys(),那么我会在插入之前从键中获取下一个值。

于 2008-10-20T02:44:57.333 回答