Skip to content Skip to sidebar Skip to footer

Insert If Not Exists?

I'm prompting a user to add an item to an SQLiteDb. When they click add, I want to check if that item already exists... if it doesn't then I want to insert it. I make the call mDbH

Solution 1:

Use the REPLACE command

Solution 2:

In such situation I perfrom such checking:

if (!checkRecordExist(DATABASE_TABLE, newString[] {KEY_1, KEY_2}, newString[] {value_1, value_2})) 
database.insert(DATABASE_TABLE, null, updateValues);

where

privatebooleancheckRecordExist(String tableName, String[] keys, String [] values) {
    StringBuilder sb = newStringBuilder();
    for (int i = 0; i < keys.length; i++) {
        sb.append(keys[i])
            .append("=\"")
            .append(values[i])
            .append("\" ");
        if (i<keys.length-1) sb.append("AND ");
    }

    Cursor cursor = database.query(tableName, null, sb.toString(), null, null, null, null);
    boolean exists = (cursor.getCount() > 0);
    cursor.close();
    return exists;
}

Solution 3:

Add a Primary Key. If you try to insert another row with the same key, the insert will fail.

Solution 4:

Have you tried using a primary key that isn't set to auto-increment? That might be why the REPLACE command isn't working

Post a Comment for "Insert If Not Exists?"