【问题标题】:Best way to get the ID of the last inserted row on SQLite获取 SQLite 上最后插入行的 ID 的最佳方法
【发布时间】:2011-08-17 13:36:08
【问题描述】:

在 iPhone 上,使用 FMDB 获取 SQLite 数据库中最后插入行的 ID 的最佳方法是什么?

有没有比做更好的方法:

SELECT MAX(ID)

【问题讨论】:

    标签: ios sql objective-c sqlite fmdb


    【解决方案1】:

    如果您可以保证您的ID 列是自增列,那么MAX(ID) 就可以了。

    但为了涵盖任何情况,有一个名为 LAST_INSERT_ROWID() 的专用 SQLite 函数:

    SELECT LAST_INSERT_ROWID();
    

    在 FMDB 中,您使用 -lastInsertRowId 方法(在内部运行上述方法):

    int lastId = [fmdb lastInsertRowId];
    

    【讨论】:

    • 为什么 [fmdb lastInsertRowId] 总是为我返回 0?
    • @landonandrey lastInsertRowId 在特定连接上工作。您正在使用的连接刚刚打开,因此没有插入行 ID。您可以参考此answer 了解更多信息。
    • 我发现LAST_INSERT_ROWID() 是特定于连接的。因此,如果您打开/关闭连接,它将无法按您预期的方式工作。
    【解决方案2】:

    函数sqlite3_last_insert_rowid() 就是您要找的。刚刚查看了 FMDB 的源代码,FMDatabase 上似乎有一个名为 -lastInsertRowId 的方法包装了该函数。

    【讨论】:

    • @FMDatabase 链接不存在
    【解决方案3】:

    尝试以下方法:

    var rowid: Int = Int(contactDB.lastInsertRowId())
    

    【讨论】:

      【解决方案4】:

      对于 swift 4 使用此代码

      let lastRowId = sqlite3_last_insert_rowid(db)
      

      例如

      if sqlite3_exec(db, stringSql, nil, nil, nil) != SQLITE_OK {
          let errmsg = String(cString: sqlite3_errmsg(db)!)
          print("error Insert: \(errmsg)")
      }
      
      let lastRowId = sqlite3_last_insert_rowid(db);
      print(lastRowId) // its gives you last insert id
      
      if sqlite3_finalize(statement) != SQLITE_OK {
          let errmsg = String(cString: sqlite3_errmsg(db)!)
          print("error finalizing prepared statement: \(errmsg)")
      }
      statement = nil
      
      //*** close data base
      if sqlite3_close(db) != SQLITE_OK {
          print("error closing database")
      }
      db = nil
      

      【讨论】:

        猜你喜欢
        • 2010-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-26
        • 1970-01-01
        相关资源
        最近更新 更多