room db update multiple rows with @query

左心房为你撑大大i 提交于 2019-12-25 03:29:07

问题


I would like to update multiple rows in a room database. But I don't have the objects - I have only the ids.

If I update one row I write something like this to my DAO:

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

With multiple rows I would need something like this:

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

OR

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

where I write something like '(1,4,7,15)' to my ids-String

Can someone tell me a good way to make such an update

because something like

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

does not seem to be a good solution


回答1:


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

But keep in mind if your list of ids contains more than 999 items SQLite will throw an exception:

SQLiteException too many SQL variables (Sqlite code 1)




回答2:


This is what you need for doing your work.

    @Query("Update brand_table set  name = :name where id In (:ids)")
    void updateBrands(List<Integer> ids, String name);


来源:https://stackoverflow.com/questions/53630852/room-db-update-multiple-rows-with-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!