【问题标题】:How to get last insert Id in SQLite?如何在 SQLite 中获取最后一个插入 ID?
【发布时间】:2026-02-11 15:50:02
【问题描述】:

SQLite 中是否有任何内置函数可用于获取最后插入的行 ID。 例如:- 在 mysql 中,我们有 LAST_INSERT_ID() 这种函数。对于 sqllite,任何可用于执行相同过程的函数。

请帮帮我。

谢谢

【问题讨论】:

标签: php sql sqlite function lastinsertid


【解决方案1】:

SQLite

这可以使用SQLite last_insert_rowid() function

last_insert_rowid() 函数返回最后一行的 ROWID 从调用该函数的数据库连接中插入。这 last_insert_rowid() SQL 函数是对 sqlite3_last_insert_rowid() C/C++接口函数。

PHP

这个函数的PHP版本/绑定是sqlite_last_insert_rowid():

返回最近插入到 数据库 dbhandle,如果它是作为自动增量字段创建的。

【讨论】:

  • 注意使用这个函数不是“线程安全的”,所以如果另一个线程同时插入一些东西,可能是错误的。
  • @rogerdpack,你有参考说明这不是线程安全的吗?答案中提供的参考说明它提供了最后一行插入 “来自调用函数的数据库连接” - 这会让我认为它 线程安全的,除非您有多个线程使用相同的连接。然而,如果您有多个线程通过不同的连接插入,那么每个线程将正确地看到同一线程插入的最后一行 ID(这通常是它的用途,与 OP 想要模仿的 LAST_INSERT_ID() 相同)。
  • @MikeThomson 公平问题:sqlite.org/c3ref/last_insert_rowid.html“如果在 sqlite3_last_insert_rowid() 函数正在运行时一个单独的线程在同一个数据库连接上执行新的 INSERT 并因此更改了最后一个插入 rowid,则返回的值通过 sqlite3_last_insert_rowid() 是不可预测的,可能不等于旧的或新的最后插入 rowid。”另见*.com/q/2127138/32453
【解决方案2】:

当使用 SQLite 版本 3 和 PDO SQLite 时,可能是这样的:

$insert = "INSERT INTO `module` (`mid`,`description`) VALUES (
            NULL,
            :text
            );
        ";
$stmt = $conn->prepare($insert);
$stmt->execute(array(':text'=> $text));

echo $conn->lastInsertId()

【讨论】:

    【解决方案3】:

    它有last_insert_rowid()

    last_insert_rowid() 函数返回最后一行的 ROWID 从调用函数的数据库连接插入

    【讨论】:

      【解决方案4】:
      【解决方案5】:

      这是一个适合我的简短 C# 方法。 Int32 对于我的目的来说足够大了。

      public static Int32 GetNextID( SqliteConnection AConnection )
      {
        Int32 result = -1;
      
        using ( SqliteCommand cmd = AConnection.CreateCommand() )
        {
          cmd.CommandText = "SELECT last_insert_rowid();";
          using ( SqliteDataReader r = cmd.ExecuteReader() )
          {
            if ( r.Read() )
              result = (Int32) r.GetInt64( 0 );
          }
        }
      
        return result;
      }
      

      【讨论】: