目录
1.导入依赖库
2.数据实体类
3.数据访问对象 (DAO)
4.数据库类
5.调用DAO里面的“增、删、改、查”方法
6.数据库升降级处理
升级(保存数据库历史数据):
升级(不保存数据库历史数据):
降级(不保存数据库历史数据):
1.导入依赖库
kapt "androidx.room:room-compiler:2.2.5"
api("androidx.room:room-ktx:2.2.5"
2.数据实体类
@Entity(tableName = "areas", indices = [Index(value = ["id"], unique = true)])
data class Area(
@PrimaryKey(autoGenerate = true)
val id: Int,
/*国家*/
val country: String? = "",
/*省、州*/
val state: String? = "",
/*城市*/
val city: String? = "",
/*省、州代码*/
val stateCode: String? = "",
/*城市代码*/
val cityCode: String? = "",
/*国家代码*/
val countryCode: String? = "",
/*新增时间*/
val addTime: Long? = 0L,
/*更新时间*/
val updateTime: Long? = 0L,
/*新增时间字符串*/
val addTimeStr: String? = "",
/*更新时间字符串*/
val updateTimeStr: String? = "",
val isDelete: Int,
/*语言*/
val language: String
)
3.数据访问对象 (DAO)
@Dao
interface AreaDao {
/**
* 获取所有国家列表(以国家ID分组)
*/
@Query("SELECT * FROM areas WHERE language=:language GROUP BY countryCode")
fun getCountryList(language: String): List<Area>
/**
* 获取所有州/省列表
*/
@Query("SELECT * FROM areas WHERE countryCode=:countryCode AND language=:language GROUP BY stateCode")
fun getStateList(countryCode: String, language: String): List<Area>
/**
* 获取所有城市列表
*/
@Query("SELECT * FROM areas WHERE countryCode=:countryCode AND stateCode=:stateCode AND language=:language GROUP BY cityCode")
fun getCityList(countryCode: String, stateCode: String, language: String): List<Area>
/**
* 获取所有城市列表
*/
@Query("SELECT * FROM areas WHERE countryCode=:countryCode AND language=:language GROUP BY cityCode")
fun getCityList(countryCode: String, language: String): List<Area>
/**
* 批量插入地区记录
*/
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAreas(tunnels: List<Area>): List<Long>
/**
* 删除所有地区记录
*/
@Query("DELETE FROM areas")
fun deleteAllArea()
}
4.数据库类
@Database(
entities = [Area::class, AlarmClock::class, DeviceInfo::class],
version = 4, exportSchema = false
)
abstract class FlowFitDatabase : RoomDatabase() {
abstract fun areaDao(): AreaDao
abstract fun alarmClockDao(): AlarmClockDao
abstract fun deviceInfoDao(): DeviceInfoDao
companion object {
/*单例模式*/
@Volatile
private var instance: FlowFitDatabase? = null
fun getInstance(context: Context): FlowFitDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
/*创建并填充数据库*/
private fun buildDatabase(context: Context): FlowFitDatabase {
return Room.databaseBuilder(
context,
FlowFitDatabase::class.java,
FLOW_FIT_DATABASE_NAME
)
.addMigrations(object : Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) {
database.execSQL("drop table IF EXISTS StepTimeSharing ")
database.execSQL(
"CREATE TABLE IF NOT EXISTS \"StepTimeSharing\" ( " +
" \"date\" INTEGER NOT NULL, " +
" \"calories\" INTEGER NOT NULL, " +
" \"distances\" INTEGER NOT NULL, " +
" \"steps\" INTEGER NOT NULL, " +
" PRIMARY KEY (\"date\") " +
");"
)
}
})
.addCallback(object : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
GlobalScope.launch(Dispatchers.IO) {
val database: FlowFitDatabase = getInstance(context)
/*初始化闹钟提醒记录*/
database.alarmClockDao().insertAll(
listOf(
AlarmClock(
id = 0,
time = 0L,
repeat = 0,
isOpen = 0,
hour = 0,
minute = 0,
label = 0,
isShow = 0
)
)
)
}
}
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
}
})
.fallbackToDestructiveMigrationOnDowngrade()//降级的时候,当未匹配到版本的时候就会直接删除表然后重新创建
// .fallbackToDestructiveMigration() //升级,清空数据库
.build()
}
}
}
5.调用DAO里面的“增、删、改、查”方法
//获取所有国家列表
FlowFitDatabase.getInstance(CONTEXT).areaDao().getCountryList(language)
6.数据库升降级处理
处理代码已包含在步骤4中:
升级(保存数据库历史数据):
1.修改version版本号
2.添加升级适配代码文章来源:https://www.toymoban.com/news/detail-569671.html
文章来源地址https://www.toymoban.com/news/detail-569671.html
升级(不保存数据库历史数据):
.fallbackToDestructiveMigration() //升级,清空数据库
降级(不保存数据库历史数据):
.fallbackToDestructiveMigrationOnDowngrade()//降级的时候,当未匹配到版本的时候就会直接删除表然后重新创建
到了这里,关于kotlin中使用Room数据库(包含升降级崩溃处理)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!