php 如何在 SQLite 中获取最后一个插入 ID?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8892973/
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-08-26 05:43:33  来源:igfitidea点击:

How to get last insert Id in SQLite?

phpsqlsqlitefunctionlastinsertid

提问by DEVOPS

Is there any built in function available in SQLite to fetch last inserted row id. For eg :- In mysql we have LAST_INSERT_ID()this kind of a function. For sqllite any function available for doing the same process.

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

Please help me.

请帮我。

Thanks

谢谢

回答by Treffynnon

SQLite

SQLite

This is available using the SQLite last_insert_rowid()function:

这可以使用SQLitelast_insert_rowid()函数获得

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

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

PHP

PHP

The PHP version/binding of this function is sqlite_last_insert_rowid():

此函数的 PHP 版本/绑定是sqlite_last_insert_rowid()

Returns the rowid of the row that was most recently inserted into the database dbhandle, if it was created as an auto-increment field.

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

回答by Behzad-Ravanbakhsh

When Using SQLite version 3 with PDO SQLite, It can be like this:

将 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()

回答by Alex K.

It has last_insert_rowid()

它有 last_insert_rowid()

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function

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

回答by Gary Z

This is a short C# method that is working for me. Int32 is large enough for my purposes.

这是一个对我有用的简短的 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;
}