Android和SQLite - 从表中检索最大ID

问题描述 投票:7回答:4

我正在尝试创建从我的表中检索最大ID的方法,但我有问题。

这是我的方法。它工作正常,但返回值为0,

public int getLastId() {
    openDB();
    int id = 0;
    final String MY_QUERY = "SELECT MAX(_id) AS _id FROM organize";
    Cursor mCursor = mDb.rawQuery(MY_QUERY, null);  
    try {
          if (mCursor.getCount() > 0) {
            mCursor.moveToFirst();
            id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));
          }
        } catch (Exception e) {
          System.out.println(e.getMessage());
        } finally {
            closeDB();
        }
return id;

}

我能解决这个问题,非常感谢

android sqlite
4个回答
6
投票

重写这一行

id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));

id = mCursor.getInt(mCursor.getColumnIndex("_id"));  

或者更好

id = mCursor.getInt(0);//there's only 1 column in cursor since you only get MAX, not dataset

看看LogCat,它会告诉你你的问题。


2
投票
final String MY_QUERY = "SELECT MAX(_id) FROM organize";

试试这个


1
投票

您是否检查过try块中的代码是否完美? 可能是代码跳转到catch块,id返回0已初始化。


1
投票

试试这个方法:

private int getMaxID(){
    int mx=-1;
    try{
        db = this.getReadableDatabase();

        SQLiteDatabase db=this.getReadableDatabase();
        Cursor cursor=db.rawQuery("SELECT max(ID) from tblIntents ",new String [] {});
        if (cursor != null)
            if(cursor.moveToFirst())
            {

                mx= cursor.getInt(0);

            }
        //  cursor.close();

        return mx;
    }
    catch(Exception e){

        return -1;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.