How to get the row count of a query in Android usi

2019-02-02 22:51发布

How do I get the row count of a query in Android using SQLite? It seems my following method does not work.

public int getFragmentCountByMixId(int mixId) {
    int count = 0;
    SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

    Cursor cursor = db.rawQuery(
        "select count(*) from downloadedFragement where mixId=?",
        new String[]{String.valueOf(mixId)});
    while(cursor.moveToFirst()){
        count = cursor.getInt(0);
    }
    return count;
}    

8条回答
SAY GOODBYE
2楼-- · 2019-02-02 22:53

Query for _ID column in table and then call getCount on cursor. Here is a link I am doing in one of my project. Look at line number 110.

查看更多
beautiful°
3楼-- · 2019-02-02 22:57
cursor.moveToNext();
cursor.getCount();

If the moveToNext() is not called, the cursorIndexOutOfBoundException may arise.

查看更多
ら.Afraid
4楼-- · 2019-02-02 22:59
戒情不戒烟
5楼-- · 2019-02-02 23:02
 public long getRecords() {
    return DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM contacts", null);
}

You can use this as a method or use this if your database uses auto increment

 public long getRecords() {
    return DatabaseUtils.longForQuery(db, "SELECT seq FROM sqlite_sequence", null);
}
查看更多
Rolldiameter
6楼-- · 2019-02-02 23:08

In DatabaseUtils

public static long queryNumEntries(SQLiteDatabase db, String table)
查看更多
地球回转人心会变
7楼-- · 2019-02-02 23:11

This would be more efficient because work for all versions:

int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);

or

int numRows = DatabaseUtils.queryNumEntries(db, "table_name");

or if you want to get number of rows which specific selection then you should go with (added in API 11)

public static long queryNumEntries (SQLiteDatabase db, String table, String selection)

Thanks :)

查看更多
登录 后发表回答