簡體   English   中英

如何使用 SQLite 獲取 Android 中查詢的行數?

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

如何使用 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.moveToNext();
cursor.getCount();

如果未調用 moveToNext(),則可能會出現 cursorIndexOutOfBoundException。

這會更有效,因為適用於所有版本:

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

或者

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

或者如果您想獲得特定選擇的行數,那么您應該使用 go (在 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();

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

查詢表中的 _ID 列,然后在 cursor 上調用 getCount。 這是我在我的一個項目中做的一個鏈接 查看第 110 行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM