4

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

E. Reuter
  • 79
  • 1
  • 8

2 Answers2

14
@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)

kphil
  • 891
  • 1
  • 9
  • 14
5

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);
Mohammad Asheri
  • 322
  • 1
  • 7