Muhammad Nabeel Arif
Muhammad Nabeel Arif

Reputation: 19310

SQLite "INSERT OR REPLACE INTO" not working

I have to write a query in sqlite to update the record if it exists or insert it if the record do not already exists. I have looked the syntax of INSERT OR REPLACE INTO from here. But in my case, when I execute the query below many times the record is duplicated. i.e If I execute the query 5 times the record is inserted 5 times.

INSERT OR REPLACE INTO NICKS 
    (id_nick,name_nick,date_creation)
 VALUES 
    ('nabeelarif', 'Muhammad Nabeel','2012-03-04')

Have you any idea what I am doing wrong. I am working on android platform and using 'Firefox Sqlite Manager' to test my query.

Upvotes: 12

Views: 17504

Answers (3)

TotoroTotoro
TotoroTotoro

Reputation: 17622

In Android, you should use SQLiteDatabase.replace(), which does insert or update. With the Android SQLite implementation, you normally don't use raw queries represented as strings. See http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#replace%28java.lang.String,%20java.lang.String,%20android.content.ContentValues%29

Upvotes: 5

Jan-Henk
Jan-Henk

Reputation: 4874

Do you have a primary key or unique index defined for your table? I believe the attributes that make up the primary key or a unique index are used to determine if a row already exists or not.

Upvotes: 4

Brad
Brad

Reputation: 5498

You need to have a unique index on one or a combination of those columns.

CREATE UNIQUE INDEX idx_something ON NICKS (id_nick, name_nick, date_creation);

Upvotes: 29

Related Questions