概要
Androidは、SQLiteというデータベースを利用できるようになっています。
機能面として、検索、挿入、更新、削除といった、基本的な処理、
また、トランザクションの機能も備えています。
以下は、sqliteでサポートされているデータ型です。
| 型 | 説明 |
| INTEGER | 符号付整数 |
| REAL | 浮動小数点数 |
| TEXT | テキスト |
| BLOB | バイナリ |
使用するポイント
・データを永続的に蓄積したい場合
・大量データを作成、読み出し、更新、削除をする場合
・データの管理を容易にしたい
SQL Helperを使ってデータベースをコントロールする
SQLiteOpenHelperという便利なクラスがあり、このクラスを利用することより、
データベースの手続きを簡略化できるようになっています。
また、データベース操作に使うAPIパッケージは、
「android.database.sqlite」になります。
それでは、前置きはこのぐらいにして、SQLiteOpenHelperを使い、DBアクセス周りの解説をしていきます。
内容としては、最終回で解説するメモ帳アプリのデータベースアクセス周りを切り出したものになります。
データベース名:memo.db
テーブル名:memo
| カラム | 内容 |
| _id | プライマリーキー |
| content | テキスト型 |
| created | テキスト型 |
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
// データーベース名を記載
static final String DATABASE_NAME = "memo.db";
// データベースのバージョン
// ①(カラムの追加などで、変更を加えた場合、カウントアップする)
static final int DATABASE_VERSION = 2;
// 継承している親クラスにデータベース名とバージョンをセット
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* ④テーブルの定義
* テーブルの作成(初期データの投入も出来る)
*/
@Override
public void onCreate( SQLiteDatabase db ) {
// テーブルを作成
db.execSQL(
"create table memo ("
+ "_id integer primary key autoincrement not null,"
+ "content text not null,"
+ "created text not null"
+ ");"
);
// ここで、初期データ挿入可能
}
/**
* ⑤データベースのバージョンアップ時の処理
* この例では、古いバージョン時には、createdがなかった為、新しく定義し直している。
*/
@Override
public void onUpgrade( SQLiteDatabase db, int oldVersion, int newVersion ) {
if( oldVersion == 1 && newVersion == 2 ){
db.execSQL(
"create table memo ("
+ "_id integer primary key autoincrement not null,"
+ "content text not null,"
+ "created text not null"
+ ");"
);
}
}
public SQLiteDatabase open() {
return super.getWritableDatabase();
}
public void close(){
super.close();
}
}
次に、データアクセスオブジェクトであるクラスを作成し、追加(insert)、検索(select)、更新(update)、削除(delete)にわけ、記載していきます。
MemoDao.java
public class MemoDao extends DatabaseHelper{
protected Context mContext = null;
protected SQLiteDatabase mDb = null;
public MemoDao(Context context) {
super(context);
mContext = context;
}
/** データベースオープン */
public void connection() {
DatabaseHelper helper = new DatabaseHelper(mContext);
mDb = helper.open();
}
/** データベースクローズ */
public void close() {
mDb.close();
mDb = null;
}
/** データを投入 */
public long addMemo( String content ){
String dateNow = String.valueOf(DateFormat.format(
"yyyy-MM-dd kk:mm:ss", Calendar.getInstance()));
ContentValues val = new ContentValues();
val.put( "content", content );
val.put( "created", dateNow );
return mDb.insert( "memo", null, val);
}
/** データを読込む */
public ArrayList> searchAllByWord(String word){
ArrayList> memoLists = new ArrayList>();
String[] selectArgs = new String[]{ word };
Cursor cursor = null;
try{
cursor = mDb.rawQuery(
"select * from memo where content like '%' || ? || '%' order by created desc;"
, selectArgs);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
HashMap memoList = new HashMap();
memoList.put("id", id);
memoList.put("content", content);
memoList.put("created", created);
memoLists.add(memoList);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return memoLists;
}
/** データを読込む */
public ArrayList> searchAll(){
ArrayList> memoLists = new ArrayList>();
Cursor cursor = null;
try{
cursor = mDb.rawQuery("select * from memo order by created desc;", null);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
Log.d("memo", "内容:"+content + " 作成日:" + created);
HashMap memoList = new HashMap();
memoList.put("id", id);
memoList.put("content", content);
memoList.put("created", created);
memoLists.add(memoList);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return memoLists;
}
/** メモIDで検索 */
public HashMap searchById( String memoId ){
String[] selectArgs = new String[]{ memoId };
Cursor cursor = null;
HashMap map = new HashMap();
try{
cursor = mDb.rawQuery("select * from memo WHERE _id = ?", selectArgs);
while(cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
map.put("id", id);
map.put("content", content);
map.put("created", created);
Log.d("memo", "内容:"+content + " 作成日:" + created);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return map;
}
/** メモを更新 */
public int updateContentById( String memoId, String content ){
String[] selectArgs = new String[]{ memoId };
ContentValues val = new ContentValues();
val.put("content", content);
return mDb.update( "memo",
val,
"_id = ?",
selectArgs);
}
/** メモの内容を条件に削除 */
public int delById( String id ){
String[] selectArgs = new String[]{ id };
return mDb.delete( "memo",
"_id = ?",
selectArgs);
}
/** 全削除 */
public int delAll(){
return mDb.delete( "memo", null, null );
}
}
追加
/** データを投入 */
public long addMemo( String content ){
String dateNow = String.valueOf(DateFormat.format(
"yyyy-MM-dd kk:mm:ss", Calendar.getInstance()));
ContentValues val = new ContentValues();
val.put( "content", content );
val.put( "created", dateNow );
return mDb.insert( "memo", null, val);
}
検索
/** データを読込む */
public ArrayList> searchAllByWord(String word){
ArrayList> memoLists = new ArrayList>();
String[] selectArgs = new String[]{ word };
Cursor cursor = null;
try{
cursor = mDb.rawQuery(
"select * from memo where content like '%' || ? || '%' order by created desc;"
, selectArgs);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
HashMap memoList = new HashMap();
memoList.put("id", id);
memoList.put("content", content);
memoList.put("created", created);
memoLists.add(memoList);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return memoLists;
}
/** データを読込む */
public ArrayList> searchAll(){
ArrayList> memoLists = new ArrayList>();
Cursor cursor = null;
try{
cursor = mDb.rawQuery("select * from memo order by created desc;", null);
while(cursor.moveToNext()) {
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
Log.d("memo", "内容:"+content + " 作成日:" + created);
HashMap memoList = new HashMap();
memoList.put("id", id);
memoList.put("content", content);
memoList.put("created", created);
memoLists.add(memoList);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return memoLists;
}
/** メモIDで検索 */
public HashMap searchById( String memoId ){
String[] selectArgs = new String[]{ memoId };
Cursor cursor = null;
HashMap map = new HashMap();
try{
cursor = mDb.rawQuery("select * from memo WHERE _id = ?", selectArgs);
while(cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex("_id"));
String content = cursor.getString(cursor.getColumnIndex("content"));
String created = cursor.getString(cursor.getColumnIndex("created"));
map.put("id", id);
map.put("content", content);
map.put("created", created);
Log.d("memo", "内容:"+content + " 作成日:" + created);
}
}
finally{
if( cursor != null ){
cursor.close();
}
}
return map;
}
更新
/** メモを更新 */
public int updateContentById( String memoId, String content ){
String[] selectArgs = new String[]{ memoId };
ContentValues val = new ContentValues();
val.put("content", content);
return mDb.update( "memo",
val,
"_id = ?",
selectArgs);
}
削除
/** メモの内容を条件に削除 */
public int delById( String id ){
String[] selectArgs = new String[]{ id };
return mDb.delete( "memo",
"_id = ?",
selectArgs);
}
/** 全削除 */
public int delAll(){
return mDb.delete( "memo", null, null );
}
データアクセス
それでは、これまで定義してきた、データベースにアクセスするメソッドを実際に呼び出し、データベースを操作します
ArrayList> memoLists;
MemoDao dao = new MemoDao(getApplicationContext());
dao.connection();
// 全てのデータの読み込み
memoLists = dao.searchAll();
// メモ内容から検索
memoLists = dao.searchAllByWord(searchWord);
// メモ内容を追加
memoDao.addMemo(content));
// メモデータ更新
memoDao.updateContentById(memoId, content);
// メモIDからメモを削除
memoDao.delById(memoId);
dao.close();
以上、Androidにおけるデータベースの使い方でした。