这是我的简单函数:
public int countCats(String tableName) {
int catCount = 0;
Cursor cursor = database.rawQuery("SELECT COUNT(*) FROM " + MySQLiteHelper.TABLE_CAT, null);
if (cursor != null) {
catCount = cursor.getColumnIndex("COUNT");
}
return catCount;
}
这个表有 11 行。但是这个函数返回-1。如何处理这个问题?
编辑:
我已经更新到这个:
public int countCats(String tableName) {
int catCount = 0;
Cursor cursor = database.rawQuery("SELECT COUNT("+ MySQLiteHelper.COLUMN_CAT+ ") FROM " + MySQLiteHelper.TABLE_CAT, null);
if (cursor.moveToFirst()) {
catCount = cursor.getInt(0);
}
cursor.close();
return catCount;
}
现在我得到 0
;
最佳答案
您只是请求游标中不存在的 COUNT
列的列索引。因此返回 -1。
要检索计数值,将光标移动到第一行并获取第一列值:
if (cursor.moveToFirst()) {
catCount = cursor.getInt(0);
}
(COUNT(*)
查询总是有一个结果行,但无论如何检查 moveToFirst()
的结果是一个好习惯。)
关于java - 在 Android SQLite 表中返回 Count(*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927104/