如何从SQL数据库中检索行数据 - Android

时间:2015-03-02 21:53:11

标签: android sql

我使用此代码将数据添加到数据库中

/**
 * Storing deck
 * */
public void addDeck(String id, String name, String uid, String did) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_DECK_ID, id); // ID
    values.put(KEY_DECK_NAME, name); // Name
    values.put(KEY_DECK_UID, uid); // Unique Id
    values.put(KEY_DECK_DID, did); // Deck id

    // Inserting Row
    db.insert(TABLE_DECK, null, values);
    db.close(); // Closing database connection
}

现在我希望能够访问每一行,我该怎么做?

这是我当前访问数据库中行的代码

// Getting deck data from database
public HashMap<String, String> getDeckDetails(){
    HashMap<String,String> deck = new HashMap<String,String>();
    String selectQuery = "SELECT * FROM " + TABLE_DECK;

    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);
    // Move to first row
    cursor.moveToFirst();
    if(cursor.getCount() > 0){
        deck.put("id", cursor.getString(1));
        deck.put("name", cursor.getString(2));
        deck.put("uid", cursor.getString(3));
        deck.put("did", cursor.getString(4));
    }
    cursor.close();
    db.close();
    // return user
    return deck;
}

此代码仅返回第一行,如何让它返回每一行?

1 个答案:

答案 0 :(得分:1)

你必须使用一个循环:

Cursor cursor = db.rawQuery(selectQuery, null);
while( cursor.moveToNext() ){
    deck.put("id", cursor.getString(1));
    deck.put("name", cursor.getString(2));
    deck.put("uid", cursor.getString(3));
    deck.put("did", cursor.getString(4));
}
cursor.close();

另外,{而不是cursor.getString(3)我会使用:

int uidPos = cursor.getColumnIndex( "uid" );
if( -1 != uidPos ) cursor.getString( uidPos );

因为它更安全