Room是Google官方提供的数据库ORM框架,使用起来非常方便。
首先添加依赖:
implementation "androidx.room:room-runtime:2.4.1"kapt "androidx.room:room-compiler:2.3.0"implementation("androidx.room:room-ktx:2.4.1")
然后写一个和数据库表对应的类:
@Entitydata class BackupData( @PrimaryKey(autoGenerate = true) var id: Int = -1, var type: String = "WeiXin", var name: String = "WeiXin", var firstTime: Long = 0L, var lastTime: Long = 0L)
使用@Entity来标记这个数据类,使用@PrimaryKey标记主键。如果使用联合主键,写法如下:
@Entity(primaryKeys=["groupId","userId"])
数据库操作的Dao:
@Daointerface AppDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun saveOrUpdateBackup(backup: BackupData): Long @Query("select * from BackupData where type=:type limit 1") fun queryBackup(type: String): Flow @Query("delete from BackupData") fun deleteBackup(): Int?}
RoomDatabase:
@Database(version = 1, entities = [BackupData::class])abstract class AppDatabase : RoomDatabase() { abstract fun appDao(): AppDao companion object { private lateinit var i: AppDatabase fun init(app: Application) { i = Room.databaseBuilder(app, AppDatabase::class.java, "app_database") .fallbackToDestructiveMigration() .build() } fun dao(): AppDao { return i.appDao() } }}
上面的代码对待数据库的版本升级是最简单粗暴的,会直接删除旧的版本,使用最新的版本。
使用的例子:
//保存或更新AppDatabase.dao().saveOrUpdateBackup(backupData)……//查询操作viewModelScope.launch(Dispatchers.IO) { AppDatabase.dao().queryBackup("WeiXin").collect { launch(Dispatchers.Main) { backupData = it } }}……//删除操作AppDatabase.dao().deleteBackup()
特别声明:以上内容(如有图片或视频亦包括在内)为自媒体平台“网易号”用户上传并发布,本平台仅提供信息存储服务。
Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.