2011-06-15 198 views
47

如何使用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; 
}  
+0

无关的问题: 您无法通过调用 “moveToFirst” 无限循环的光标。你应该调用它一次,然后使用while(cursor.moveToNext()){... – Ankhwatcher 2017-10-26 16:02:56

回答

100
+4

我不知道这将如何与您当前的实现工作,但如果你只是改变计数(*)为*,这应该工作。 – Noel 2011-06-15 00:18:57

+2

我认为最好的解决方案'返回(int)DatabaseUtils.longForQuery(mDB,“SELECT COUNT(*)FROM table_name”,null);' – 2015-09-11 07:42:14

+0

这将返回0为1游标的游标。 – 2015-11-20 17:01:20

0

查询用于表_ID柱,然后调用getCount将上光标。这是我在我的一个项目中做的link。看线数110

0

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

如果使用MoveToNext()不被调用,则cursorIndexOutOfBoundException可能出现。

+0

我不这么认为 – 2015-09-11 07:47:49

2

这将是更有效,因为所有版本的工作:

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) 

谢谢:)

0

DatabaseUtils

public static long queryNumEntries(SQLiteDatabase db, String table) 
+0

如果它是内存数据库,没有数据库名称会怎么样? – 2015-11-20 17:02:40

+0

“DatabaseUtils.queryNumEntries”仍然是一个不错的选择还是已被弃用? – AJW 2016-01-09 16:55:35