Haiyuan Li
Haiyuan Li

Reputation: 377

How to get the primary key (e.g. ID) of just inserted to SQLITE DB in most efficient way?

for instance: a table created as below:

create table tbl_text( id integer primary key, txt text unique, ref integer );

insert a record:

insert into tbl_text values(null, "Hello", 123);

how to get the id of "Hello" just inserted in fastest way? query works but it might be time-consuming, e.g.

select id from tbl_text where txt='Hello'

Upvotes: 1

Views: 820

Answers (2)

Chris Fulstow
Chris Fulstow

Reputation: 41902

Take a look at sqlite3_last_insert_rowid(), from the docs it returns the rowid of the most recent successful INSERT into the database from the database connection.

Upvotes: 2

Adam Wenger
Adam Wenger

Reputation: 17570

You can use last_insert_rowid() or sqlite3_last_insert_rowid() depending on how you're accessing sqlite. Watch out for another thread running an insert on the same connection, more about that in their documentation

Upvotes: 2

Related Questions