PG備忘録

プログラミングいろいろ

SQLiteの使い方① データベースの作成

①SQLiteOpenHelperを実装したMyDBHelperクラスをつくる→データベースの設定をする

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) {
    }
}


②MainActivityでデータベースを作る

MyDBHelper helper = new MyDBHelper(this);
SQLiteDatabase db = helper.getWritableDatabase();

メソッドの説明

SQLiteOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version)

・context: コンテキスト
MainActivityの中でthisを受け取る
・name: データベースの名前
・factory: nullでok
・version: データベースのバージョン; 大体1でok

void onCreate(SQLiteDatabase db)

データベースが初めて作られるときに呼ばれるメソッド

void execSQL(String sql)

・string: SQL文をいれる
SELECT以外のCREATE, INSERT, DELETEなどデータを受け取らないSQL文を受け取れる

void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

データベースがバージョンアップしたときに呼び出される
大体中身は空でok

SQLiteDatabase getWritableDatabase()

読み書き可能なデータベースをつくる


参考サイト:
https://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.htmldeveloper.android.com
https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.htmldeveloper.android.com
it-trick-java.appspot.com
www.appli-info.jp