Cursor result = db.rawQuery("SELECT 學號 FROM grade WHERE 學號 = 123", null);
if (???) { // 這裡該怎麼寫?
Toast.makeText(this, "學號不存在", Toast.LENGTH_SHORT).show();
}
result.moveToFirst() / result.getCount() 需額外移動游標、釋放資源,代碼冗長// 1. SQL 層面直接返回計數
Cursor cursor = db.rawQuery("SELECT COUNT(*) FROM grade WHERE 學號 = ?", new String[]{"123"});
int count = 0;
if (cursor.moveToFirst()) {
count = cursor.getInt(0); // 第 0 列即 COUNT(*) 結果
}
cursor.close();
if (count == 0) {
Toast.makeText(this, "學號不存在", Toast.LENGTH_SHORT).show();
}
public boolean exists(SQLiteDatabase db, String table, String whereClause, String[] whereArgs) {
String sql = "SELECT COUNT(*) FROM " + table + " WHERE " + whereClause;
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, whereArgs);
return cursor.moveToFirst() && cursor.getInt(0) > 0;
} finally {
if (cursor != null) cursor.close();
}
}
// 調用示例
if (!exists(db, "grade", "學號 = ?", new String[]{"123"})) {
Toast.makeText(this, "學號不存在", Toast.LENGTH_SHORT).show();
}
| 方案 | IO 開銷 | 內存佔用 | 代碼複雜度 |
|---|---|---|---|
| SELECT 列 + Cursor.getCount() | 讀取所有匹配行 | 較高 | 中等 |
| SELECT COUNT(*) | 僅掃描索引/統計信息 | 極低(單行單列) | 低 |
| EXISTS 子查詢(SQLite 不直接支持) | - | - | - |
「只查所需,聚合下推」——判斷存在性時,讓數據庫引擎完成計數,應用層只取一個整數。