ともちゃんのアプリ開発日記

組込みC言語プログラマだったともちゃんが、四苦八苦しながら、AndroidのJAVA/Kotlin、iOSのSwiftUIを習得して行きます。ともちゃんの備忘録も兼ねています。

SQLiteの使い方:データベースのOpen

SQLiteの使い方:データベースのOpenのサンプルコードです。

public class MainActivity extends AppCompatActivity {

static final String DB = "sqlite_sample.db";
static final int DB_VERSION = 1;
static final String CREATE_TABLE = "create table mytable ( _id integer primary key autoincrement, date text not null, weight real not null, body_fat_percentage real not null );";
static final String DROP_TABLE = "drop table mytable;";

static SQLiteDatabase mydb;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
(中略)
MySQLiteOpenHelper hlpr = new MySQLiteOpenHelper(getApplicationContext());
mydb = hlpr.getWritableDatabase();
}
     private class MySQLiteOpenHelper extends SQLiteOpenHelper { 
public MySQLiteOpenHelper(Context c) {
super(c, DB, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DROP_TABLE);
onCreate(db);
}
}
}