在 iPhone 上,使用 FMDB 获取 SQLite 数据库中最后插入行的 ID 的最佳方法是什么?
有没有更好的方法而不是这样做:
SELECT MAX(ID)
在 iPhone 上,使用 FMDB 获取 SQLite 数据库中最后插入行的 ID 的最佳方法是什么?
有没有更好的方法而不是这样做:
SELECT MAX(ID)
如果您可以保证您的ID
列是自动增量列,那MAX(ID)
就没问题了。
但是为了涵盖任何情况,有一个专门的 SQLite 函数称为LAST_INSERT_ROWID()
:
SELECT LAST_INSERT_ROWID();
在 FMDB 中,您使用-lastInsertRowId
方法(在内部运行上述方法):
int lastId = [fmdb lastInsertRowId];
函数sqlite3_last_insert_rowid()是您正在寻找的。刚刚检查了 FMDB 的源代码,FMDatabase 上似乎有一个方法被称为-lastInsertRowId
包装函数。
对于 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
尝试以下操作:
var rowid: Int = Int(contactDB.lastInsertRowId())