2011-06-15 26 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

相關問題