简体   繁体   中英

In Android ContentProvider backed by SQLite, how should I implement insertOrUpdate semantics?

This is in the case where there is a UNIQUE column apart from the _id column.

I can see three options:

  1. Leave insert as insert-if-no-conflict, and update as update-if-present (this seems to be the "standard"), and perform all the work on the client to decide how to resolve this.

  2. Change insert to insert-or-update-if-present and leave update as update-if-present. Does this break the standard ContentProvider contract?

  3. Change update to update-or-insert-if-not-present and leave insert as insert-if-no-conflict. This makes less sense than the second option above to me, so I'll probably not do this - but I suspect it's pretty similar in the end.

Additionally, if I do the first option, is there any advantage in doing

  1. query then if count=1, replace, else insert
  2. insert, if failed replace
  3. replace, if failed insert.

I anticipate more updates than replaces overall, but am mainly concerned with making this maintainable, as I don't expect this to be a performance bottleneck.

My inclination will be to query and then update or insert based on if there is an existing record. You can use the existing ContentProvider methods for this - and it will be quite readable for subsequent developers to understand.

The downside is there's a couple of unnecessary DB hits.

The article talks through how you could modify the ContentProvider to 'implement' insertOrUpdate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM