使用insertWithOnConflict进行更新或插入 [英] Using insertWithOnConflict for update or insert
问题描述
我需要插入或更新,并且找到了SQLiteDatabase的方法insertWithOnConflict,但是我不知道它如何检查条目是否已经存在.
I need to insert or update and I found the method insertWithOnConflict of the SQLiteDatabase, but I do not know how it checks if the entry already exists.
从理论上讲,我需要一个"Where"参数来检查某个ID是否存在,如果存在,则应替换所有其他列.
Theoretically I need a "Where" argument to check if a certain ID exists, and if so, it should replace all other columns.
这就是我现在拥有的,但是我不认为第二个参数是唯一的ID
This is what I have now, but I don´t think that the second argument is the unique id
ContentValues args = new ContentValues();
args.put(AppDatabase.COLUMN_ID, entry.getId());
args.put(AppDatabase.COLUMN_NAME, entry.getAppname());
args.put(AppDatabase.COLUMN_URL, entry.getAppUrl());
database.insertWithOnConflict(AppDatabase.TABLE_FILELIST, COLUMN_ID, args, SQLiteDatabase.CONFLICT_REPLACE);
我该如何管理这种行为?
How can I manage this behaviour?
推荐答案
-
确保您的表中有一些适当的约束,例如
PRIMARY KEY
或UNIQUE
.
插入时,通过ContentValues
将一个值添加到此约束列中.如果插入新行会违反某些约束,则首先删除冲突的行,然后再插入新行.
When inserting, add a value to this constrained column via ContentValues
. If inserting the new row would violate some constraint, the conflicting rows are first deleted and then the new row is inserted.
在您的情况下,COLUMN_ID
看起来很适合PRIMARY KEY
约束.无需在代码中使用值COLUMN_ID
的第二个arg nullColumnHack
,您可以将其作为null
传递.
In your case, COLUMN_ID
looks like a good candidate for PRIMARY KEY
constraint. The second arg nullColumnHack
with value COLUMN_ID
in your code is not necessary, you can pass it as null
.
这篇关于使用insertWithOnConflict进行更新或插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!