• kotlin中使用Room数据库(包含升降级崩溃处理)


    目录

    1.导入依赖库

    2.数据实体类

    3.数据访问对象 (DAO)

    4.数据库类

    5.调用DAO里面的“增、删、改、查”方法

    6.数据库升降级处理

    升级(保存数据库历史数据):

    升级(不保存数据库历史数据):

    降级(不保存数据库历史数据):


    1.导入依赖库

    1. kapt "androidx.room:room-compiler:2.2.5"
    2. api("androidx.room:room-ktx:2.2.5"

    2.数据实体类

    1. @Entity(tableName = "areas", indices = [Index(value = ["id"], unique = true)])
    2. data class Area(
    3. @PrimaryKey(autoGenerate = true)
    4. val id: Int,
    5. /*国家*/
    6. val country: String? = "",
    7. /*省、州*/
    8. val state: String? = "",
    9. /*城市*/
    10. val city: String? = "",
    11. /*省、州代码*/
    12. val stateCode: String? = "",
    13. /*城市代码*/
    14. val cityCode: String? = "",
    15. /*国家代码*/
    16. val countryCode: String? = "",
    17. /*新增时间*/
    18. val addTime: Long? = 0L,
    19. /*更新时间*/
    20. val updateTime: Long? = 0L,
    21. /*新增时间字符串*/
    22. val addTimeStr: String? = "",
    23. /*更新时间字符串*/
    24. val updateTimeStr: String? = "",
    25. val isDelete: Int,
    26. /*语言*/
    27. val language: String
    28. )

    3.数据访问对象 (DAO)

    1. @Dao
    2. interface AreaDao {
    3. /**
    4. * 获取所有国家列表(以国家ID分组)
    5. */
    6. @Query("SELECT * FROM areas WHERE language=:language GROUP BY countryCode")
    7. fun getCountryList(language: String): List
    8. /**
    9. * 获取所有州/省列表
    10. */
    11. @Query("SELECT * FROM areas WHERE countryCode=:countryCode AND language=:language GROUP BY stateCode")
    12. fun getStateList(countryCode: String, language: String): List
    13. /**
    14. * 获取所有城市列表
    15. */
    16. @Query("SELECT * FROM areas WHERE countryCode=:countryCode AND stateCode=:stateCode AND language=:language GROUP BY cityCode")
    17. fun getCityList(countryCode: String, stateCode: String, language: String): List
    18. /**
    19. * 获取所有城市列表
    20. */
    21. @Query("SELECT * FROM areas WHERE countryCode=:countryCode AND language=:language GROUP BY cityCode")
    22. fun getCityList(countryCode: String, language: String): List
    23. /**
    24. * 批量插入地区记录
    25. */
    26. @Insert(onConflict = OnConflictStrategy.REPLACE)
    27. fun insertAreas(tunnels: List<Area>): List<Long>
    28. /**
    29. * 删除所有地区记录
    30. */
    31. @Query("DELETE FROM areas")
    32. fun deleteAllArea()
    33. }

    4.数据库类

    1. @Database(
    2. entities = [Area::class, AlarmClock::class, DeviceInfo::class],
    3. version = 4, exportSchema = false
    4. )
    5. abstract class FlowFitDatabase : RoomDatabase() {
    6. abstract fun areaDao(): AreaDao
    7. abstract fun alarmClockDao(): AlarmClockDao
    8. abstract fun deviceInfoDao(): DeviceInfoDao
    9. companion object {
    10. /*单例模式*/
    11. @Volatile
    12. private var instance: FlowFitDatabase? = null
    13. fun getInstance(context: Context): FlowFitDatabase {
    14. return instance ?: synchronized(this) {
    15. instance ?: buildDatabase(context).also { instance = it }
    16. }
    17. }
    18. /*创建并填充数据库*/
    19. private fun buildDatabase(context: Context): FlowFitDatabase {
    20. return Room.databaseBuilder(
    21. context,
    22. FlowFitDatabase::class.java,
    23. FLOW_FIT_DATABASE_NAME
    24. )
    25. .addMigrations(object : Migration(1, 2) {
    26. override fun migrate(database: SupportSQLiteDatabase) {
    27. database.execSQL("drop table IF EXISTS StepTimeSharing ")
    28. database.execSQL(
    29. "CREATE TABLE IF NOT EXISTS \"StepTimeSharing\" ( " +
    30. " \"date\" INTEGER NOT NULL, " +
    31. " \"calories\" INTEGER NOT NULL, " +
    32. " \"distances\" INTEGER NOT NULL, " +
    33. " \"steps\" INTEGER NOT NULL, " +
    34. " PRIMARY KEY (\"date\") " +
    35. ");"
    36. )
    37. }
    38. })
    39. .addCallback(object : RoomDatabase.Callback() {
    40. override fun onCreate(db: SupportSQLiteDatabase) {
    41. super.onCreate(db)
    42. GlobalScope.launch(Dispatchers.IO) {
    43. val database: FlowFitDatabase = getInstance(context)
    44. /*初始化闹钟提醒记录*/
    45. database.alarmClockDao().insertAll(
    46. listOf(
    47. AlarmClock(
    48. id = 0,
    49. time = 0L,
    50. repeat = 0,
    51. isOpen = 0,
    52. hour = 0,
    53. minute = 0,
    54. label = 0,
    55. isShow = 0
    56. )
    57. )
    58. )
    59. }
    60. }
    61. override fun onOpen(db: SupportSQLiteDatabase) {
    62. super.onOpen(db)
    63. }
    64. })
    65. .fallbackToDestructiveMigrationOnDowngrade()//降级的时候,当未匹配到版本的时候就会直接删除表然后重新创建
    66. // .fallbackToDestructiveMigration() //升级,清空数据库
    67. .build()
    68. }
    69. }
    70. }

    5.调用DAO里面的“增、删、改、查”方法

    1. //获取所有国家列表
    2. FlowFitDatabase.getInstance(CONTEXT).areaDao().getCountryList(language)

    6.数据库升降级处理

    处理代码已包含在步骤4中:

    升级(保存数据库历史数据):

    1.修改version版本号

    2.添加升级适配代码

    升级(不保存数据库历史数据):
    .fallbackToDestructiveMigration() //升级,清空数据库
    降级(不保存数据库历史数据):
    .fallbackToDestructiveMigrationOnDowngrade()//降级的时候,当未匹配到版本的时候就会直接删除表然后重新创建

  • 相关阅读:
    Android Studio 导出 jar
    io模型初探
    51.【结构体初始化的两种方法】
    【YashanDB知识库】PHP使用OCI接口使用数据库绑定参数功能异常
    你真知道交换机、路由器和防火墙的区别吗?
    【C++ 学习】链接、作用域、内存管理
    centos7下centos-home磁盘空间转移到centos-root下
    京东数据报告:2023年8月京东手机行业品牌销售排行榜
    Vite中的CSS工程化方案
    ZooKeeper下载、安装、配置和使用
  • 原文地址:https://blog.csdn.net/jin_pan/article/details/131718988