Android SQLite ON CONFLICT UPDATE是可能的吗?

时间:2021-03-28 05:32:37

I need to solve this problem.

我需要解决这个问题。

I started my project from the wrong concept that ON CONFLICT REPLACE will do an update of the row content when it finds a conflict. Also I was thinking that in that insert (with the conflict) if I don't put a value for a column it wont do the replace but keep the old value. Instead I just discovered that the ON CONFLICT REPLACE if it finds a conflict it will do a delete->insert and if it can't find a value for a column (where I put null for not updating the field) it will replace the null value with the default column value in order to make successfully the insert.

我从错误的概念开始我的项目,ON CONFLICT REPLACE会在发现冲突时更新行内容。另外我在想那个插入(有冲突)如果我没有为列添加值,它不会进行替换但保留旧值。相反,我刚刚发现ON CONFLICT REPLACE如果发现冲突它将执行delete-> insert并且如果它找不到列的值(我将null放置为不更新字段)它将替换null使用默认列值的值,以便成功插入。

So know I have this big root problem :D

所以知道我有这个根本问题:D

As you understand what I want to reach is this:

如你所知,我想要达到的目的是:

I always do the insert, if it finds already a row with the same unique keys (conflict) it will only update the values. If for a field it wont find the values ( I don't put it in the ContentValues ) it wont update those field but keep the old one (like a normal update query where you don't put a column for update it).

我总是进行插入,如果它找到一个具有相同唯一键(冲突)的行,它将只更新值。如果对于一个字段,它不会找到值(我没有把它放在ContentValues中)它不会更新那些字段但保留旧字段(就像一个普通的更新查询,你没有放置列来更新它)。

To solve my problem I tought these solutions:

为了解决我的问题,我尝试了这些解决方案:

  • ON CONFLICT UPDATE (this will only work when you have only 1 unique fields, if you have 2 or more unique fields that throw the conflict it will crash)
  • ON CONFLICT UPDATE(仅当您只有1个唯一字段时才会起作用,如果您有2个或更多个唯一字段会引发冲突,它会崩溃)
  • UPDATE ON FAIL INSERT where it always try to do an update. If it fails because it can't find the row related to the record (it's not yet present in the db) it will try to do an insert
  • 更新失败插入,它总是尝试进行更新。如果它失败,因为它找不到与记录相关的行(它还没有出现在数据库中),它会尝试插入

Some one has already thought about this problem and has a solution? Or maybe we can just try to find a solution :)

有人已经考虑过这个问题并有解决方案吗?或者也许我们可以尝试找到一个解决方案:)

I think that the best way is to keep things on low level (db level) in order to keep a good level of performance.

我认为最好的方法是将事物保持在低级别(db级别)以保持良好的性能水平。

1 个解决方案

#1


7  

Following SQLite3 official Documentation is not possible to automatically do a ON CONFLICT UPDATE but only a REPLACE that is like DELETE -> INSERT (new values).

在SQLite3之后,官方文档无法自动执行ON CONFLICT UPDATE,而只能执行类似DELETE - > INSERT(新值)的REPLACE。

#1


7  

Following SQLite3 official Documentation is not possible to automatically do a ON CONFLICT UPDATE but only a REPLACE that is like DELETE -> INSERT (new values).

在SQLite3之后,官方文档无法自动执行ON CONFLICT UPDATE,而只能执行类似DELETE - > INSERT(新值)的REPLACE。