2014-03-27 18 views
0

我有一個SQLite數據庫,其中我正嘗試使用ID讀取數據庫中的最後8行。基於SQLite中的ID查詢最後N行

我在查詢時遇到問題。似乎無法做到。

public String lastEightRows(){ 
    String[] columns = new String[] {KEY_ROWID, KEY_COLORS}; 
    String result30 = " "; 

    String where = "ORDER BY" + KEY_ROWID + "DESC LIMIT" + 8; 
    //This is where I am not able to get the query right 

    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, where, null, null, null, null); 

    int iRow = c.getColumnIndex(KEY_ROWID); 
    int iColors = c.getColumnIndex(KEY_COLORS); 

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ 
     result30 = result30 + c.getString(iRow) + " " + c.getString(iColors) + " " + "\n"; 
    } 

    return result30; 
} 

我得到這個錯誤消息

03-26 22:58:27.420: E/AndroidRuntime(1368): android.database.sqlite.SQLiteException: near "DESC": syntax error (code 1): , while compiling: SELECT _id, persons_colors FROM personsTable WHERE _id DESC LIMIT 8 
+0

什麼是我們的數據庫?它的contentresolver或sqliteDatabase? – Amadas

+0

sqlitedatabase的名稱 – artist

+0

你的錯誤是什麼?你調試你的應用程序? – Sree

回答

1

Android SQLiteDatabase API

公共光標查詢(字符串表,字符串[]列,字符串選擇的String [] selectionArgs兩個,字符串GROUPBY ,字符串有,字符串orderBy,字符串限制)

查詢給定的表,返回一個光標的結果設置。

試試這個代碼()定義query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)
所以,儘量改變這種代替

Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, KEY_ROWID + " DESC", "8"); 
+0

謝謝你的工作。我沒有在查詢的權利。 – artist

0

sqlitedatabase.query。

Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, KEY_ROWID + " DESC", "8"); 
+0

如果行數小於8,我可以做類似這樣的事情:Cursor c = ourDatabase.query(DATABASE_TABLE,columns,null,null,null,KEY_ROWID +「DESC」,「<= 8」); – artist

+0

@artist我不知道。我知道限制不支持'<', '>','='等運營商。我想如果你想要的話,你可以使用遊標的值來創建函數。 – Amadas