快速取得 SQLite 資料表總行數,不需載入所有資料。
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM my_table", null);
int count = 0;
if (cursor.moveToFirst()) {
count = cursor.getInt(0); // 第 0 欄即為 COUNT(*) 結果
}
cursor.close();
// count 即為 my_table 總行數
public long getTableRowCount(SQLiteDatabase db, String tableName) {
// 防 SQL 注入:驗證表名 (簡易示範)
if (!tableName.matches("[a-zA-Z_][a-zA-Z0-9_]*")) {
throw new IllegalArgumentException("Invalid table name: " + tableName);
}
String query = "SELECT COUNT(*) FROM " + tableName;
Cursor cursor = null;
try {
cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
return cursor.getLong(0);
}
return 0;
} finally {
if (cursor != null) cursor.close();
}
}
// 使用
long count = getTableRowCount(db, "my_table");
| 方法 | 效能 | 適用場景 |
|---|---|---|
SELECT COUNT(*) | 最快 (只掃描索引/統計資訊) | 大量資料、頻繁查詢 |
DatabaseUtils.queryNumEntries(db, table) | 同上 (內部用 COUNT(*)) | 簡潔 API、API 11+ |
cursor.getCount() (查詢所有行) | 極慢 (載入所有資料到 Cursor) | **禁止用於統計行數** |
import android.database.DatabaseUtils;
long count = DatabaseUtils.queryNumEntries(db, "my_table");
// 等同於 SELECT COUNT(*),但更簡潔
// 統計符合條件的行數
public long countWhere(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) {
String query = "SELECT COUNT(*) FROM " + table + " WHERE " + whereClause;
Cursor cursor = db.rawQuery(query, whereArgs);
try {
return cursor.moveToFirst() ? cursor.getLong(0) : 0;
} finally {
cursor.close();
}
}
// 使用:統計 name 以 "A" 開頭的行數
long count = countWhere(db, "my_table", "name LIKE ?", new String[]{"A%"});