问题
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.
Theoretically I need a "Where" argument to check if a certain ID exists, and if so, it should replace all other columns.
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?
回答1:
Make sure you have some appropriate constraint in your table, such as
PRIMARY KEY
orUNIQUE
.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.
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
.
来源:https://stackoverflow.com/questions/22644531/using-insertwithonconflict-for-update-or-insert