room db 使用@query 更新多行

room db update multiple rows with @query

我想更新房间数据库中的多行。但我没有对象 - 我只有 ID。

如果我更新一行,我会在我的 DAO 中写入这样的内容:

@Query("UPDATE items SET place = :new_place WHERE id = :id;")
fun updateItemPlace(id:Int, new_place:String)

对于多行,我需要这样的东西:

@Query("UPDATE items SET place = :new_place WHERE id = :ids;")
fun updateItemPlaces(ids:List<Int>, new_place:String)

@Query("UPDATE items SET place = :new_place WHERE id IN :ids;")
fun updateItemPlaces(ids:String, new_place:String)

我在我的 ids-String 中写了类似“(1,4,7,15)”的内容

谁能告诉我进行此类更新的好方法

因为像

val ids = ListOf(1,4,7,15)
ids.forEach{
    itemDao.updateItemPlace(it,'new place')
}

似乎不​​是一个好的解决方案

这是您工作所需要的。

    @Query("Update brand_table set  name = :name where id In (:ids)")
    void updateBrands(List<Integer> ids, String name);
@Query("UPDATE items SET place = :new_place WHERE id IN (:ids)")
fun updateItemPlaces(ids:List<Int>, new_place:String)

但请记住,如果您的 ID 列表包含超过 999 个项目,SQLite 将抛出异常:

SQLiteException too many SQL variables (Sqlite code 1)