且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android的SQLite的光标出的SELECT COUNT(*)FROM表越界异常

更新时间:2023-12-01 14:03:52

您错过了

mcursor.moveToFirst();

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

但是,你应该用更好的方法完成这个任务,就像DatabaseUtils的内置助手

But you should use better methods for this task, like the inbuilt helpers of DatabaseUtils

public long count() {
    return DatabaseUtils.queryNumEntries(db,'tablename');
}

您可能会发现有助于使用 DatabaseUtils.longForQuery()拿到第一列长值,当你在哪里查询的总数。它的简单,你不需要是一堆工作的光标。

You might find helpful to use DatabaseUtils.longForQuery() to get the first column long value, when you have where query for the total count. It's simpler and you do not need that bunch of work with the Cursor.