如何使用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;
}
8个解决方案
105 votes
Cursor.getCount()
michaelg answered 2020-01-23T01:12:24Z
7 votes
cursor.moveToNext();
cursor.getCount();
如果未调用moveToNext(),则可能会出现cursorIndexOutOfBoundException。
Pramod Setlur answered 2020-01-23T01:12:44Z
4 votes
这将更加有效,因为适用于所有版本:
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)
谢谢 :)
Pratik Butani answered 2020-01-23T01:13:17Z
1 votes
使用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();
LK Yeung answered 2020-01-23T01:13:37Z
0 votes
查询表中的_ID列,然后在游标上调用getCount。 这是我在一个项目中正在做的链接。 查看行号110。
Gopal answered 2020-01-23T01:13:57Z
0 votes
在DatabaseUtils
public static long queryNumEntries(SQLiteDatabase db, String table)
James Wierzba answered 2020-01-23T01:14:16Z
0 votes
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);
}
Rohit answered 2020-01-23T01:14:36Z
0 votes
val query = "SELECT * FROM $TABLE_NAME ;"
val result = db.rawQuery(query,null)
Toast.makeText(ctx,result.count,Toast.LENGTH_SHORT).show()
Stan answered 2020-01-23T01:14:52Z