Best way to get the ID of the last inserted row on SQLite

陌路散爱 提交于 2019-12-29 03:52:04

问题


On iPhone, what's the best way to get the ID of the last inserted row on an SQLite Database using FMDB ?

Is there a better way rather than doing :

SELECT MAX(ID)

回答1:


If you can guarantee that your ID column is an auto-increment column, MAX(ID) is fine.

But to cover any case, there's a specialized SQLite function called LAST_INSERT_ROWID():

SELECT LAST_INSERT_ROWID();

In FMDB, you use the -lastInsertRowId method (which internally runs the above):

int lastId = [fmdb lastInsertRowId];



回答2:


The function sqlite3_last_insert_rowid() is what you're looking for. Having just checked out the source code for FMDB, there seems to be a method on FMDatabase called -lastInsertRowId that wraps the function.




回答3:


Try the following:

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



回答4:


For swift 4 use this code

let lastRowId = sqlite3_last_insert_rowid(db)

for example

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


来源:https://stackoverflow.com/questions/5867404/best-way-to-get-the-id-of-the-last-inserted-row-on-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!