lundi 22 décembre 2014

How to update a set of rows based on their (different) primary keys in SQLite (Android)?

I have a database table that consists of several columns, including id (the primary key) and last_sync (a timestamp). A background process synchronizes the rows of the table occasionally with a server.


If the process is successful, it returns ...



  • one single timestamp, which represents the time of the synchronization

  • a list of ids. This means that the rows which belong to these ids were successfully synchronized


What I want to do now is to update the last_sync column of every row whose id is in the list with the new timestamp.




Example:



  • returned timestamp: 143394245

  • returned list: [11,25,64,126]


After the update, the last_sync column of rows 11, 25, 64 and 126 should equal 143394245.




How could I do this the most efficient way? The list could contain several thousand ids.


The easiest (but most expensive) way would be to iterate over the list and execute an update-statement for every id (update ... set last_sync = ... where id = ...) which would result in 1000 updates if the list has 1000 entries. This is of course not what I want to do, especially not on a mobile device.


Another idea would be to do something like update ... set last_sync = ... where id IN (...). The set next to IN would contain all of the ids. But how to create that set dynamically.. with a StringBuilder? I think that's very hacky..


I hope there are other ways. Any help is appreciated, thanks.


Aucun commentaire:

Enregistrer un commentaire