vdaubry
vdaubry

Reputation: 11439

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

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)

Upvotes: 29

Views: 24671

Answers (4)

Bijender Singh Shekhawat
Bijender Singh Shekhawat

Reputation: 4484

For swift 5 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

Upvotes: 5

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 9

Michele Diblasi
Michele Diblasi

Reputation: 67

Try the following:

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

Upvotes: 1

BoltClock
BoltClock

Reputation: 723598

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];

Upvotes: 66

Related Questions