Cursorについてもう少し
みなさん、こんにちは。
今回も当校の授業の中で生徒さんが混乱しがちな点を解説します。
前回はSQLite3データベースの使用方法を説明しがてら、Cursorにも少し触れました。
今回はCursorについてもう少し掘り下げてみたいと思います。
Cursorってそもそもなに?
カーソル(Cursor)はデータベースから取得したデータを表す際によく使われる考え方です。
Cursorは、データベースのテーブルと同じように2次元の表形式となっています。
縦軸がカラム、横軸をロウと呼びます。
尚、データベース内のテーブルと、Cursorと、ListViewの関係は下図の通りです。
データベースの内容が、一旦Cursorに保存され、それをListViewにセットしているイメージです。
Cursor
データベースを操作するときにはいくつかSQLを使います。
- INSERT
- UPDATE
- SELECT
- DELETE
これらはデータベースオブジェクトを取得したのち、以下のように使用します。
1 2 3 4 5 6 7 8 | // insert db.insert(String table, String nullColumnHack, ContentValues values); // update db.update(String table, ContentValues values, String whereClause, String[] whereArgs); // delete db.delete(String table, String whereClause, String[] whereArgs); |
具体例で確認してみましょう。
以下は2通りの方法で試していますが、どちらも結果は同じです。
- execSQL()を使用しない場合
- execSQL()を使用する場合
1 2 3 4 5 6 7 8 9 10 11 12 13 | // insert() ContentValues insertValues = new ContentValues(); insertValues.put( "name" , "山田太郎" ); insertValues.put( "number" , 24 ); db.insert(person, name, insertValues); // update ContentValues updateValues = new ContentValues(); updateValues.put( "number" , 7 ); db.update(person, updateValues, "name = ?" , new String[] { "山田太郎" }); // delete db.delete(person, "name = ?" , new String[] { "山田太郎" }); |
また、以下のようにexecSQL()メソッドを使用することも可能です。
1 2 3 4 5 6 7 8 | // insert db.execSQL( "insert into person (name,age) values('山田太郎',24)" ); // update db.execSQL( "update person set age = 7 where name = '山田太郎'" ); // delete db.execSQL( "delete from person where (name = '山田太郎') " ); |
実はexecSQL()は戻り値がありません。
それ故、SELECTのみexecSQL()は使用できないので、以下のように記述します。
1 2 3 4 5 | // select その1 db.query (String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit); // select その2 db.rawQueryWithFactory (SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable); |
上記2つに関して、query()メソッドは単純なSQLによるデータを取得する際に利用し、複雑なSQLを実行する場合はrawQuery()を使用します。
それでは同じ意味合いのSQLを2つの方法で試してみましょう。
- query()の場合
- rawQuery()の場合
1 | Cursor c = db.query( "person" , new String[] { "name" , "age" }, "id >= ?" , new String[] { "5" }, null , null , null ); |
1 | Cursor c = db.rawQuery( "select name, age from person where id >= ?;" , new String[] { "5" }); |
少しごちゃごちゃしていてわかりにくいのですが、用途や好みで使い分けができるということですね。
たくさん使って慣れていきましょう。
本日はここまでとします。