使用行标识从sqlitedatabase获取特定数据

时间:2014-03-18 23:02:55

标签: android

我在数据库中有两列,id和city。当行id小于3时,如何获取所有城市数据并将其放入字符串中。当行id小于3时,我很难编写查询来获取数据。现在我的方法得到所有来自数据库的数据。感谢。

String[] columns = new String[]{KEY_ROWID, KEY_CITY};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result =" ";
int iRow = c.getColumnIndex(KEY_ROWID);

 int iCity = c.getColumnIndex(KEY_CITY);


for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){


result = result + c.getString(iCity)  + "\n"; 


}



return result;

1 个答案:

答案 0 :(得分:1)

    String[] columns = new String[]{KEY_ROWID, KEY_CITY};

    // "note "rowid" is used in fts tables and "id" in normal tables.
    // I'm assuming your constant KEY_ROWID chose the correct one.

    String where = KEY_ROWID + " <= " + 3;  

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


    if(!cursor.moveToFirst()){
        Log.e("System.out", "cursor is empty");
    }else{

        int ix_city = cursor.getColumnIndexOrThrow(KEY_CITY);

        StringBuilder sb = new StringBuilder();


        do{
            String city = cursor.getString(ix_city);
            Log.i("System.out", "city name " + city);

            if(TextUtils.isEmpty(city))
                  continue;

            sb.append(city).append("\n");
        }while(cursor.moveToNext());

        Log.i("System.out", "the entire list " + sb.toString());

    }