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

问题描述:

下面的函数是给我一个出界异常...

The following function is giving me an out of bounds exception...

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

它的意思返回在数据库中的行数。任何人都知道什么是错了吗?我也许我完成这个任务的方法不对?

It's meant to return the number of rows in the database. Anybody know whats wrong? am I perhaps doing this task the wrong way?

您错过了

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.