[android] SQLiteでのCursorのループ方法

SQLiteでのCursorのループ方法

    // DBをオープンして、簡単なクエリーを投げる
    SQLiteOpenHelper helper = new DBOpenHelper(this);
    SQLiteDatabase db = helper.getReadableDatabase();
    Cursor cursor = db
            .rawQuery("select * from TEST_TABLE", new String[] {});

    // 方式1:forを使ったループ
    for (boolean next = cursor.moveToFirst(); next; next = cursor
            .moveToNext()) {
        // ・・・処理
        Log.d("sql", "code1 data=" + cursor.getString(1));
    }

    // 方式2:whileを使ったループ
    boolean next = cursor.moveToFirst();
    while (next) {
        // ・・・処理
        Log.d("sql", "code2 data=" + cursor.getString(1));

        // 次のレコード
        next = cursor.moveToNext();
    }

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です