SQLiteの使い方(SQLiteOpenHelperクラス)~その1~

SQLiteのデータベースを作成し、エディットテキストから入力したデータを登録し、画面に表示するサンプルを作ってみました。

「データベース一覧」に、データベースに登録されているデータが表示されます。

データベース SQLiteの使い方の画像

「five」と入力して、追加ボタンを押すと、一覧に「5:five」と表示され、データベースにデータが追加されていきます。

データベース SQLiteの使い方の画像

◆◆◆SQLiteOpenHelperクラスを継承したクラスの実装◆◆◆

public class MyDBHelper extends SQLiteOpenHelper {

public MyDBHelper(Context context) {
//DBを作成
super(context, “testdb”, null , 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(“CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)”);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

「onCreate」は、データベースを作成した時に呼び出されるメソッドで、「onUpgrade」は、データベースをバージョンアップした時に呼び出されるメソッド。「onCreate」に、データベースのテーブルを作成するコードを書くことが多い

◆◆◆データベースの生成◆◆◆
public MyDBHelper(Context context) {
//ストレージ(ローカルファイル)にDBを作成
super(context, “testdb”, null , 1);
}

第一引数:コンテキスト
第二引数:データベースの名前(String型)
第三引数:とりあえず null にしておけば大丈夫だと思います。(CursorFactory型)
第四引数:データベースのバージョン番号(int型)

◆◆◆SQLの実行◆◆◆
db.execSQL(“CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)”);

” “の中にSQL文を書いて実行することができる。テーブルを作成するだけでなく、レコードの追加(INSERT)、更新(UPDATE)、削除(DELETE)なども実行できる。ただし、検索(SELECT)は発行されないらしいので、db.queryを使う

◆◆◆データベース(レコード)の削除◆◆◆
db.delete(“testtb”, null, null);

第一引数:テーブル名
第二引数、第三引数:SQLのWHERE条件文を作成するための引数。

例えば
db.delete(“testtb”, “_id = ?”, new String[]{“1”});
を実行すると、_id=1のレコードが削除される。
(引数を二つに分けているのは、SQLインジェクション対策だと思われます。)

◆◆◆データベース(レコード)の検索◆◆◆
Cursor c = db.query(“testtb”, new String[] {“_id”, “comment”}, null, null, null, null, null);

第一引数:テーブル名
第二引数:取得するカラム名
第三引数、第四引数:条件文作成のための引数
第五引数:groupBy句の引数
第六引数:having句の引数
第七引数:orderBy句の引数
戻り値はCusor型のオブジェクト

◆◆◆カーソルの使い方◆◆◆
startManagingCursor(c);
while(c.moveToNext()) {
/*データがなくなるまで、ループ処理が繰り返される。
str += c.getString(c.getColumnIndex(“_id”)) + “:” +
c.getString(c.getColumnIndex(“comment”)) + “\n”;
}

startManagingCursor(Cursor c)は、カーソルを自動で管理してくれるメソッドで、このメソッドを呼び出した後、c.moveToNextを呼び出すと、カーソルが最初のデータに移動します。そのあとに、c.moveToNextを呼び出すとデータがなくなるまで、次のデータにカーソルが移動します
c.moveToFirstでも、最初のデータに移動することができますが、カーソルを使い終わった後に、c.closeをする必要があります。これをしないと、デバッグの際にSQLiteCursor.finalize()で強制終了してしまいます。startManagingCursor(Cursor c)は、カーソルのcloseを自動でしてくれるみたいなので、必要ありません。)

◆◆◆データベース(レコード)の追加◆◆◆
db.insert(“testtb”, null, values);

第一引数:テーブル名(String型)
第二引数:nullColumnHack。とりあえずnullで大丈夫だと思います。(String型)
第三引数:カラム値を格納したContentValues型の引数(ContentValues型)

◆◆◆ContentValuesに値を追加する。◆◆◆
ContentValues values = new ContentValues();
values.put(“comment”, edittext.getText().toString());

第一引数:キー値(カラム値)(String型)
第二引数:値(String型、integer型、Long型など)

↓↓↓修正または追加したファイルのコードは以下の通りです。↓↓↓
(それ以外は、新規プロジェクトを生成した時のものと同じです。)

「DBSampleA.java」のサンプルコード

package com.sample.android.dbsamplea;

import java.io.File;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DBSampleA extends Activity implements View.OnClickListener{

	private Button btn;
    private EditText edittext;
    private TextView textview;
    private MyDBHelper myhelper;
    private String str;
    private static SQLiteDatabase db;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //ボタンの生成
        btn = (Button)findViewById(R.id.AddButton);
        btn.setOnClickListener(this);

        //エディットテキストの生成
        edittext = (EditText)findViewById(R.id.AddEditText);

        //テキストビューの生成
        textview = (TextView)findViewById(R.id.MyTextView);

        //データベースヘルパーの生成
        myhelper = new MyDBHelper(this);
        db = myhelper.getWritableDatabase();

        //データベーステーブルクリア
        db.delete("testtb", null, null);

        //データベースのデータを読み取って表示する。
        Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null);
        startManagingCursor(c);
        str = "データベース一覧\n";
        while(c.moveToNext()) {
        	str += c.getString(c.getColumnIndex("_id")) + ":" +
        		c.getString(c.getColumnIndex("comment")) + "\n";
        }

       	textview.setText(str);
    }

    //ボタンクリックイベントの処理
    public void onClick(View v) {

    	//データベースに、データを登録。
    	ContentValues values = new ContentValues();
    	values.put("comment", edittext.getText().toString());
    	db.insert("testtb", null, values);

    	//データベースのデータを読み取って表示する。
        Cursor c = db.query("testtb", new String[] {"_id", "comment"}, null, null, null, null, null);
        startManagingCursor(c);
        str = "データベース一覧\n";
        while(c.moveToNext()) {
        	str += c.getString(c.getColumnIndex("_id")) + ":" +
        		c.getString(c.getColumnIndex("comment")) + "\n";

        }

       	textview.setText(str);

    }

    @Override
    public void onDestroy() {
    	super.onDestroy();
    	myhelper.close();

    	//データベース削除
    	File file = new File("/data/data/com.sample.android.dbsamplea/databases/testdb");
    	file.delete();
    }
}

「MyDBHelper.java」のサンプルコード(追加ファイル)

package com.sample.android.dbsamplea;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyDBHelper extends SQLiteOpenHelper {

	public MyDBHelper(Context context) {
		//DBを作成
		super(context, "testdb", null , 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE testtb (_id INTEGER PRIMARY KEY, comment TEXT)");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

	}
}

「main.xml」のサンプルコード

< ?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<edittext android:id="@+id/AddEditText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<button android:id="@+id/AddButton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="追加"
/>
<textview android:id="@+id/MyTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</linearlayout>

中堅サーバエンジニア

中堅サーバエンジニア現在Unity勉強中

都内で10数年、Web系のアプリケーション開発をしています。 プログラミング、ゲーム、株とかのブログを書いています。

関連記事

コメント

この記事へのコメントはありません。