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

时间:2011-08-15 11:13:43

标签: android sqlite

我正在尝试创建从表中检索max 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;

}

我可以解决这个问题吗,非常感谢

4 个答案:

答案 0 :(得分: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,它会告诉你你的问题。

答案 1 :(得分:2)

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

只尝试这个

答案 2 :(得分:1)

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

答案 3 :(得分: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;
    }
}
相关问题