vendredi 7 août 2015

android sqlite unique insert

Just a simple SQLite question...

I've created a table like this:CREATE TABLE mytable (id INTEGER PRIMARY KEY AUTOINCREMENT, column1 TEXT, column2 TEXT, UNIQUE (column1, column2)) (I also tried it with the extension ON CONFLICT REPLACE)

But if I call my insert method on the second time with the same values, they will be added. E.g.

insert("one", "two"); 
insert("one", "two");

fills the table like this:

1 | one | two
2 | one | two

but it should look like this after the second call:

1 | one | two

That's my insert function:

public void insert(String a, String b){
    ContentValues contentValues = new ContentValues();
    contentValues.put("column1", a);
    contentValues.put("column2", b);
    try {
        //database.insertWithOnConflict("mytable", null, contentValues, SQLiteDatabase.CONFLICT_IGNORE);
        //database.insertWithOnConflict("mytable", null, contentValues, SQLiteDatabase.CONFLICT_REPLACE);
        database.insertOrThrow("mytable", null, contentValues);
    } catch (SQLiteConstraintException e) {
        Log.e("insert", "SQLException: " + e.getLocalizedMessage());
    }
}

Aucun commentaire:

Enregistrer un commentaire