Using insertWithOnConflict for update or insert

我是研究僧i 提交于 2019-12-19 16:54:45

问题


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:


  1. Make sure you have some appropriate constraint in your table, such as PRIMARY KEY or UNIQUE.

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!