根据SQLite中的ID查询最后N行

时间:2014-03-27 04:06:57

标签: android android-sqlite

我有一个SQLite数据库,我正在尝试使用ID读取数据库中的最后8行。

我遇到查询问题。似乎无法做对。

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

2 个答案:

答案 0 :(得分:1)

来自Android SQLiteDatabase API

  

public Cursor query(String table,String [] columns,String selection,String [] selectionArgs,String groupBy,String having,String orderBy,String limit)

     

查询给定的表,在结果集上返回一个Cursor。

尝试使用此代码

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

答案 1 :(得分:0)

sqlitedatabase.query()定义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, KEY_ROWID + " DESC", "8");