【问题标题】:Can SQLite return the id when inserting data?SQLite在插入数据时可以返回id吗?
【发布时间】:2022-05-18 21:04:59
【问题描述】:

我正在使用 sqlite3.exe 对我的数据库执行查询,使用以下代码。

public static string QueryDB(string query)
{
    string output = System.String.Empty;
    string error = System.String.Empty;

    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.FileName = "C:\\sqlite\\sqlite3.exe";
    startInfo.Arguments = "test.db " + query;
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;
    startInfo.RedirectStandardError = true;
    startInfo.RedirectStandardOutput = true;
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

    try
    {
        using(System.Diagnostics.Process sqlite3 = System.Diagnostics.Process.Start(startInfo))
        {
            output = sqlite3.StandardOutput.ReadToEnd();
            error = sqlite3.StandardError.ReadToEnd();
            sqlite3.WaitForExit();
        }
    }
    catch (System.Exception ex)
    {
        System.Console.WriteLine(ex.ToString());
        return null;
    }
    return output;
}  

我正在向表中插入数据,我希望它返回插入数据的 id。有没有办法让 SQLite 做到这一点?

例如,我的查询可能看起来像这样"INSERT INTO mytable (some_values) VALUES ('some value');"。运行此查询后,我希望output 包含插入数据的rowid。有没有办法做到这一点(命令行开关等)?


一种可能的解决方法是对数据库运行两个命令。首先插入数据,然后获取最后插入的行id。在这种情况下,查询将如下所示"\"INSERT INTO mytable (some_values) VALUES ('some value'); SELECT last_insert_rowid();\""

【问题讨论】:

  • 这不是解决方法。就是这样。
  • 你为什么要执行sqlite3.exe而不是使用本机数据库驱动程序?
  • @CL。我不知道 sqlite 的本机数据库驱动程序。

标签: sqlite


【解决方案1】:

你会考虑这个:

select max(id) from your_table_name;

或嵌入函数last_insert_rowid()

【讨论】:

    【解决方案2】:

    您不应在 DB 中使用 max(id) 或类似函数。 在这种特定情况下,它可以工作,条件是您使用一个连接和一个线程将数据写入数据库。

    如果有多个连接,您可能会得到错误的答案。

    从 SQLite 3.35.0 版本开始,它支持在插入语句中返回关闭 (SQLite Returning Close)

    create table test (
      id integer not null primary key autoincrement,
      val text
    );
    
    insert into table test(val) values (val) returning id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 2022-09-23
      • 2014-05-22
      • 1970-01-01
      • 2016-04-16
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多