@SQLiteOpenHelper クラスを継承したヘルパークラス
Aアクセスしたいテーブルのエンティティクラス
Bデータベースにアクセスするクラス
次のようなテーブルにアクセスするという例。
データベース名: sample_data
テーブル構造:
id | integer |
item | text |
@SQLiteOpenHelper クラスを継承したヘルパークラス
public class DatabaseOpenHelper extends SQLiteOpenHelper{
public DatabaseOpenHelper(Context context) {
super(context, "sample_data", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
ContentValues values = new ContentValues();
String sql = "create table sample ( id integer primary key not null, item text )";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
Aアクセスしたいテーブルのエンティティクラス
public class ItemSample {
private int id = 0;
private String item = null;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}
Bデータベースにアクセスするクラス
public class DaoSample {
private SQLiteDatabase db = null;
private DatabaseOpenHelper dbHelper = null;
public DaoSample(DatabaseOpenHelper dbHelper) {
this.dbHelper = dbHelper;
}
/**
* idをキーにレコードを検索する
*/
public ItemSample findById(int id) {
Cursor cursor = null;
ItemSample itemSample = new ItemSample();
try {
db = dbHelper.getReadableDatabase();
cursor = db.query("sample", new String[] {"id", "item"}, "id = ?", new String[] {String.valueOf(id)}, null, null, null);
while (cursor.moveToNext()) {
itemSample.setId(cursor.getInt(0));
itemSample.setItem(cursor.getString(1));
}
} catch (SQLException e) {
} finally {
if (cursor != null) cursor.close();
if (db != null) db.close();
}
return itemSample;
}
/**
* テーブルにレコードを追加する
*/
public long insert(ItemSample itemSample) {
ContentValues values = new ContentValues();
values.put("id", itemSample.getId());
values.put("item", itemSample.getItem());
long rowId = -1;
try {
db = dbHelper.getReadableDatabase();
db.beginTransaction();
rowId = db.insert("sample", null, values);
db.setTransactionSuccessful();
} catch (SQLException e) {
} finally {
if (db != null) {
db.endTransaction();
db.close();
}
}
return rowId;
}
}