How to get the row count of a query in Android using SQLite?

前提是你 提交于 2019-12-18 11:38:27

问题


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;
}    

回答1:


Cursor.getCount()




回答2:


cursor.moveToNext();
cursor.getCount();

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




回答3:


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 :)




回答4:


use String instead of int

String strCount = "";
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()){
    strCount = cursor.getString(cursor.getColumnIndex("COUNT(*)"));
}
count = Integer.valueOf(strCount).intValue();



回答5:


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.




回答6:


In DatabaseUtils

public static long queryNumEntries(SQLiteDatabase db, String table)



回答7:


 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);
}



回答8:


val query = "SELECT * FROM $TABLE_NAME ;"
val result = db.rawQuery(query,null)
Toast.makeText(ctx,result.count,Toast.LENGTH_SHORT).show()


来源:https://stackoverflow.com/questions/6351606/how-to-get-the-row-count-of-a-query-in-android-using-sqlite

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!