package com.doumee.keyCabinet.dao;
|
|
import android.content.Context;
|
|
import androidx.room.Database;
|
import androidx.room.Room;
|
import androidx.room.RoomDatabase;
|
import androidx.room.migration.Migration;
|
import androidx.sqlite.db.SupportSQLiteDatabase;
|
|
@Database(entities = {CabinetGridDo.class}, version = 1,exportSchema = false)
|
public abstract class CabinetGridDB extends RoomDatabase {
|
public abstract CabinetGridDao cabinetGridDao();
|
private static CabinetGridDB INSTANCE;
|
private static final Object sLock = new Object();
|
//数据库迁移 1-->2
|
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
|
@Override
|
public void migrate(SupportSQLiteDatabase database) {
|
database.execSQL("ALTER TABLE department ADD COLUMN phone_num TEXT");
|
//database.execSQL("ALTER TABLE department ADD COLUMN phone_num INTEGER NOT NULL DEFAULT 0");
|
}
|
};
|
//跳跃式迁移
|
static final Migration MIGRATION_2_4 = new Migration(2, 4) {
|
@Override
|
public void migrate(SupportSQLiteDatabase database) {
|
//创建表
|
database.execSQL(
|
"CREATE TABLE student_new (student_id TEXT, student_name TEXT, phone_num INTEGER, PRIMARY KEY(student_id))");
|
//复制表
|
database.execSQL(
|
"INSERT INTO student_new (student_id, student_name, phone_num) SELECT student_id, student_name, phone_num FROM student");
|
//删除表
|
database.execSQL("DROP TABLE student");
|
//修改表名称
|
database.execSQL("ALTER TABLE student_new RENAME TO students");
|
}
|
};
|
//跳跃式迁移
|
static final Migration MIGRATION_1_4 = new Migration(1, 4) {
|
@Override
|
public void migrate(SupportSQLiteDatabase database) {
|
//创建表
|
database.execSQL(
|
"CREATE TABLE student_new (student_id TEXT, student_name TEXT, phone_num INTEGER, PRIMARY KEY(student_id))");
|
//复制表
|
database.execSQL(
|
"INSERT INTO student_new (student_id, student_name, phone_num) SELECT student_id, student_name, phone_num FROM student");
|
//删除表
|
database.execSQL("DROP TABLE student");
|
//修改表名称
|
database.execSQL("ALTER TABLE student_new RENAME TO students");
|
}
|
};
|
|
public static CabinetGridDB getInstance(Context context) {
|
synchronized (sLock) {
|
if (INSTANCE == null) {
|
INSTANCE =
|
Room.databaseBuilder(context.getApplicationContext(), CabinetGridDB.class, "CabinetGrid.db")
|
.allowMainThreadQueries()//Room不允许在主线程中访问数据库
|
//.addMigrations(MIGRATION_1_2)//数据库迁移
|
//.addMigrations(MIGRATION_1_2,MIGRATION_2_4,MIGRATION_1_4)//数据库迁移 ,可以用1_4,快速迁移
|
.build();
|
}
|
return INSTANCE;
|
}
|
}
|
}
|