Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android SQLite - what does SQLiteDatabase.replace() actually do?

I need to do a INSERT or UPDATE IF EXIST type of procedure with my database. I read that .replace() was the way to go. It inserts new records just fine, but if the record already exists, it doesn't appear to update it.

I have something like this:

ContentValues values = new ContentValues(); values.put(ID, 1); values.put(NAME, "bob"); values.put(VISIBLE, true); db.replace("peopleTable", null, values); 

If I run this code when this record isn't in the database, it appears to create the record just fine, as if I did an insert(). But if I change NAME to "john" or something like that, and run the replace() again, it doesn't appear to update the record.

According to the docs, here is the syntax:

public long replace (String table, String nullColumnHack, ContentValues initialValues) 

Why is it called initalValues? Does that mean those values are only used when the record doesn't exist and it's going to be inserted? If so, how do you use the method to update a record? Where do you specify the new values?

If I am misunderstanding what replace() does altogether, can someone explain what it's purpose is?

like image 556
Jake Wilson Avatar asked Nov 02 '11 16:11

Jake Wilson


2 Answers

As I understand it replace() works much like the SQLite REPLACE keyword - a row will be updated if a unique constraint violation occurs for the insert. So the ID column in your example would need to have a PRIMARY KEY constraint in the database schema for the row to be updated.

like image 160
Jeff Gilfelt Avatar answered Sep 21 '22 12:09

Jeff Gilfelt


The replace() method actually execute the sql command insert or replace into (...) values (...)

like image 20
tarn Avatar answered Sep 23 '22 12:09

tarn