Android “SELECT last_insert_rowid()”总是返回“0”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11302276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:49:36  来源:igfitidea点击:

"SELECT last_insert_rowid()" returns always "0"

androidsqlite

提问by venni

I have a problem with "last_insert_rowid()".

我对“last_insert_rowid()”有疑问。

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

在我的 DB-Helper-Class 中,我正在执行以下操作:

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.

我总是得到“0”回来。那不可能,因为我的数据库中有很多条目,并且自动增量值应该高得多。

What I am doing wrong?

我做错了什么?

回答by venni

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

回答by Ali

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.

您不需要将表名与last_insert_rowid()它会自动从会话中选择最后插入的 id。所以你也可以简单地使用这个功能。

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