如何使用SQLite在Android中获取查询的行数?

| 如何使用SQLite在Android中获取查询的行数?看来我的以下方法无效。
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;
}    
    
已邀请:
        
Cursor.getCount()
    
        
cursor.moveToNext();
cursor.getCount();
如果未调用moveToNext(),则可能会出现cursorIndexOutOfBoundException。     
        这将更加有效,因为适用于所有版本:
int numRows = DatabaseUtils.longForQuery(db, \"SELECT COUNT(*) FROM table_name\", null);
要么
int numRows = DatabaseUtils.queryNumEntries(db, \"table_name\");
或者,如果您想获取特定选择的行数,则应该使用(在API 11中添加)
public static long queryNumEntries (SQLiteDatabase db, String table, String selection)
谢谢 :)     
        使用String而不是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();
    
        查询表中的_ID列,然后在游标上调用getCount。这是我在一个项目中正在做的链接。查看行号110。     
        在
DatabaseUtils
public static long queryNumEntries(SQLiteDatabase db, String table)
    
        
 public long getRecords() {
    return DatabaseUtils.longForQuery(db, \"SELECT COUNT(*) FROM contacts\", null);
}
您可以将其用作方法,如果数据库使用自动增量,则可以使用此方法
 public long getRecords() {
    return DatabaseUtils.longForQuery(db, \"SELECT seq FROM sqlite_sequence\", null);
}
    
        
val query = \"SELECT * FROM $TABLE_NAME ;\"
val result = db.rawQuery(query,null)
Toast.makeText(ctx,result.count,Toast.LENGTH_SHORT).show()
    

要回复问题请先登录注册