user1772982
user1772982

Reputation:

Android - how to use "select last_insert_rowid();"

I'm newbie in Android.

I want to display a new ID in the TextView. So, I just think of getting latest ID that had been store in the database and declare as Integer add 1 to the value that I get then display to the TextView.

I have read many of the question regarding the getting the latest ID. How can I use select last_insert_rowid();?

Thanks!

Upvotes: 4

Views: 8487

Answers (3)

midders
midders

Reputation: 57

Cursor c = database.rawQuery("SELECT last_insert_rowid()", null);
c.moveToFirst();
int id = c.getInt(0);
id += 1;

I'm a newbie too so can't explain very well. The above will get the last insert id from the same session. It won't work if a new session is started, ie you insert something and close the connection and reopen it, as it will then return 0 so you'll need to bear that in mind as your TextView would always show 1. As like you I read many questions about it without knowing how to implement it. The above code is how I managed to use it without getting outofbounds exceptions.

Upvotes: 3

CL.
CL.

Reputation: 180290

last_insert_rowid() works only for records that have been inserted in the same session.

If your column is declared as INTEGER PRIMARY KEY, then SQLite will automatically generate a value for it if you don't specify one in a new record.

If you really need the ID before you have inserted the record, you can execute something like this:

SELECT max(_id) FROM MyTable

Upvotes: 4

nano_nano
nano_nano

Reputation: 12524

if you use autoincrement use

SELECT * from SQLITE_SEQUENCE;

to get the latest id.

Upvotes: 3

Related Questions