如何从光标中检索数据?

时间:2014-02-21 10:28:58

标签: android sqlite android-cursor

public String getSum(String code) 
{
        SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor =db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);
    String data = cursor.getString(cursor.getColumnIndex("data"));
        return data;
    }

我想获取数据“KEY_SUM”,但它没有得到它。我怎么能这样做?

public String getSum(String code) {
    SQLiteDatabase db = this.getReadableDatabase();


    Cursor cursor =db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);

    String data = "0";
    if (cursor.moveToFirst()) 
    { 
        data = cursor.getString (cursor.getColumnIndex (KEY_SUM));
    }
    return data;
}

在我实施之后,我也无法获得价值。我只得到0。

3 个答案:

答案 0 :(得分:1)

将光标移动到第一条记录,如:

Cursor mCursor =db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new  String[] { code }, null, null, null, null)

if (mCursor != null) {
        mCursor.moveToFirst();
 String data = cursor.getString(cursor.getColumnIndex("data"));
    }

答案 1 :(得分:0)

在从光标获取数据之前,您需要编写moveToFirst();,如下所示

public String getSum(String code) 
{
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);

    if ( cursor.getCount() > 0 )
    {
        cursor.moveToFirst();                                            // Add this line
        String data = cursor.getString(cursor.getColumnIndex("data"));
        return data;
    }
    return null;
}

答案 2 :(得分:0)

 SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.query(TABLE_OWNER, new String[] { KEY_SUM }, KEY_CODE + "=?", new String[] { code }, null, null, null, null);
    if (cursor != null) {
       cursor.moveToFirst();
       if (cursor.getCount() > 0) {
           while (cursor.isAfterLast() == false) { //You need to check if cursor doesnot contain last row 
              String data = cursor.getString(cursor.getColumnIndex("data"));
              cursor.moveToNext();
           }
       }
    }