Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get newly added row in SQLite table

In my android application, I have a SQLite database containing a table with an id column with AUTOINCREMENT. I'm using an INSERT statement to add a new row but I need to immediately access this row so I can refer to it by the ID. So does anyone know of a way to get the ID of this newly added row?

Thanks!

like image 746
Hyrum Hammon Avatar asked Mar 24 '23 13:03

Hyrum Hammon


2 Answers

SQLiteDatabase.insert returns the id of the newly created row.

So, you would get the row like so:

long row = mDatabase.insert(MY_TABLE,  "id", values);

(above of course is just an example)

See here: SQliteDatabase.insert

Returns

the row ID of the newly inserted row, or -1 if an error occurred

like image 141
Ken Wolf Avatar answered Apr 01 '23 05:04

Ken Wolf


I think you can use last_insert_rowid() function

From documentation

The last_insert_rowid() function returns the ROWID of the last row insert from the database connection which invoked the function. The last_insert_rowid() SQL function is a wrapper around the sqlite3_last_insert_rowid() C/C++ interface function.

like image 23
Fabio Avatar answered Apr 01 '23 05:04

Fabio