Home » Android » java – Android SQLite – what does SQLiteDatabase.replace() actually do?

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

Posted by: admin April 23, 2020 Leave a comment

Questions:

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?

How to&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.

Answer:

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