I suggest that you ask how to INSERT new lines or UPDATE existing lines in one step. Although this is possible in one raw SQL, as discussed in this answer , I found it easier to do this in Android in two steps using SQLiteDatabase.insertWithOnConflict () , using CONFLICT_IGNORE to conflict the algorithm.,
ContentValues initialValues = new ContentValues(); initialValues.put("_id", 1); // the execution is different if _id is 2 initialValues.put("columnA", "valueNEW"); int id = (int) yourdb.insertWithOnConflict("your_table", null, initialValues, SQLiteDatabase.CONFLICT_IGNORE); if (id == -1) { yourdb.update("your_table", initialValues, "_id=?", new String[] {"1"}); // number 1 is the _id here, update to variable for your code }
This example assumes that the table key is set for the column "_id", that you know the entry _id and that there is already row # 1 (_id = 1, columnA = "valueA", columnB = "valueB"). There is a difference using insertWithOnConflict with CONFLICT_REPLACE and CONFLICT_IGNORE
- CONFLICT_REPLACE will overwrite existing values in other columns with a null value (i.e. ColumnB will become NULL, and the result will be _id = 1, columnA = "valueNEW", columnB = NULL). As a result, you will lose existing data, but I do not use them in my code.
- CONFLICT_IGNORE will skip SQL INSERT for your existing row # 1, and you will UPDATE this SQL row in the next step, saving the contents of all other columns (i.e. the result will be _id = 1, columnA = "valueNEW", columnB = "VALUE billion") .
If you try to insert a new row No. 2, which does not exist yet, the code will execute SQL INSERT only in the first insertWithOnConflict statement (that is, the result will be _id = 2, columnA = "valueNEW", columnB = NULL).
Beware of this error , which causes SQLiteDatabase.CONFLICT_IGNORE crashes in API10 (and probably API11). The request returns 0 instead of -1 when testing on Android 2.2.
If you do not know the _id record key or if you have a condition that does not create a conflict, you can change the logic to UPDATE or INSERT . This will save your _id record key during UPDATE or create a new _id record during INSERT.
int u = yourdb.update("yourtable", values, "anotherID=?", new String[]{"x"}); if (u == 0) { yourdb.insertWithOnConflict("yourtable", null, values, SQLiteDatabase.CONFLICT_REPLACE); }
The above example assumes that you just want to update the timestamp value in a record, for example. If you call insertWithOnConflict first, INSERT will create a new _id entry due to the difference in state of the timestamp.