Room delete multiple rows by WHERE IN clause not working

问题: I want to delete multiple rows by their IDs in Android Room by DELETE FROM...WHERE...IN (...) clause. Below is the code: ItemDao @Dao interface ItemDao { @Query("DE...

问题:

I want to delete multiple rows by their IDs in Android Room by DELETE FROM...WHERE...IN (...) clause. Below is the code:

ItemDao

@Dao
interface ItemDao {
    @Query("DELETE FROM Item WHERE id IN (:ids)")
    fun deleteItemByIds(ids: String)
}

ItemViewModel

class ItemViewModel(application: Application) : AndroidViewModel(application) {
    fun deleteByIds(ids: String) {
        mScope.launch(Dispatchers.IO) {
            mItemDao.deleteItemByIds(ids)
        }
    }
}

ItemActivity

fun onDelete(){
    // these are not real IDs, just for demo
    val itemIdList = arrayListOf<Long>(1, 2, 3)
    val ids = itemIdList.toString().drop(1).dropLast(1) // ids = "1, 2, 3"
    itemViewModel.deleteByIds(ids)
}

When there's only one ID, the code works. But when there are multiple IDs, it doesn't. So what happened here? Thanks for your help.


回答1:

You need to pass an array or list when you are dealing with WHERE IN clause. Like:

@Dao
interface ItemDao {
    @Query("DELETE FROM Item WHERE id IN (:ids)")
    fun deleteItemByIds(ids: Array<Long>)
}
  • 发表于 2019-03-27 16:53
  • 阅读 ( 231 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除