[英]Updating a Single Column In Room Database
That's the function I'm using for update:这就是我用于更新的功能:
private fun updateSettingsDatabase(settingsDao: SettingsDao) {
lifecycleScope.launch {
settingsDao.update(SettingsEntity(
1,
nightMode=nightModeResult,
))
}
}
@Query("SELECT * FROM `settings-table`")
fun fetchCurrentSettings(): Flow<List<SettingsEntity>>
I specified nightMode=
because I thought that this way I'm only updating this column, but it turns out that it resets every column, how do I update a single column, while keeping the values the rest of the columns?我指定
nightMode=
因为我认为这样我只更新此列,但事实证明它会重置每一列,我如何更新单个列,同时保留其余列的值?
If it is single or few columns that you want to update then you can write custom query.如果您要更新单个或几列,那么您可以编写自定义查询。
In your dao class在你的道课上
@Query("UPDATE settings-table SET nightMode = :nightModeResult WHERE id = :id")
fun updateNightMode(id: Int, nightModeResult: Any): Int
Instead of creating new SettingsEntity
object.而不是创建新的
SettingsEntity
对象。 Try to get the exact object first then update the value into it and finally update to Dao.首先尝试获取确切的对象,然后将值更新到其中,最后更新到 Dao。
For Eg.,例如,
@Query("SELECT * FROM `settings-table` where id=:id")
fun getSettingEntityById(id: Int): Flow<SettingsEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun update(entity: SettingsEntity)
private fun updateSettingsDatabase(settingsDao: SettingsDao) {
val entity = settingsDao.getSettingEntityById(1) // Replace 1 with exact id
entity.updateValue(newValue)
lifecycleScope.launch {
settingsDao.update(entity)
}
}
Hope this helps :)希望这可以帮助 :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.