Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"SELECT last_insert_rowid()" returns always "0"

Tags:

android

sqlite

I have a problem with "last_insert_rowid()".

In my DB-Helper-Class I am doing the following:

public int getLastID() {
    final String MY_QUERY = "SELECT last_insert_rowid() FROM "+ DATABASE_TABLE5;
    Cursor cur = mDb.rawQuery(MY_QUERY, null);
    cur.moveToFirst();
    int ID = cur.getInt(0);
    cur.close();
    return ID;
}

But when I call this in my intent:

int ID = mDbHelper.getLastID(); 
Toast.makeText(this, "LastID: " + ID, Toast.LENGTH_SHORT).show();

I get always "0" back. That can not be, cause I have a lot of entries in my DB and the autoincrement value should be much higher.

What I am doing wrong?

like image 680
venni Avatar asked Jul 02 '12 22:07

venni


2 Answers

OK, that was the right hint John ;-)

The query should look like this:

public int getHighestID() {
final String MY_QUERY = "SELECT MAX(_id) FROM " + DATABASE_TABLE5;
Cursor cur = mDb.rawQuery(MY_QUERY, null);
cur.moveToFirst();
int ID = cur.getInt(0);
cur.close();
return ID;
}   
like image 171
venni Avatar answered Nov 16 '22 04:11

venni


You don't need to put table name with last_insert_rowid() it will automatically select last inserted id from session. so you can just simply use this function as well.

public int getHighestID() {
    final String MY_QUERY = "SELECT last_insert_rowid()";
    Cursor cur = mDb.rawQuery(MY_QUERY, null);
    cur.moveToFirst();
    int ID = cur.getInt(0);
    cur.close();
    return ID;
}
like image 32
Husnain Ali Avatar answered Nov 16 '22 03:11

Husnain Ali