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
mDbHelper.createNote(inputLine.getText().toString().trim(), mTable[i]);
Which calls...
public long createNote(String value, String table) {
ContentValues initialValues = new ContentValues();
initialValues.put(table, va开发者_开发问答lue);
return mDb.insert(table, null, initialValues);
}
Thats works but it doesn't check if the item already exists, so it still inserts duplicates. So I tried
return mDb.insertWithOnConflict(table, null, initialValues, SQLiteDatabase.CONFLICT_FAIL);
However, it doesn't appear to recognize insertWIthOnConflict or SQLiteDatabase.CONFLICT_FAIL...
How can I get this to work?
Edit: it's 1 table, 2 rows. table name = note, rows = _id, note.
Use the REPLACE command
In such situation I perfrom such checking:
if (!checkRecordExist(DATABASE_TABLE, new String[] {KEY_1, KEY_2}, new String[] {value_1, value_2}))
database.insert(DATABASE_TABLE, null, updateValues);
where
private boolean checkRecordExist(String tableName, String[] keys, String [] values) {
StringBuilder sb = new StringBuilder();
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;
}
Add a Primary Key. If you try to insert another row with the same key, the insert will fail.
Have you tried using a primary key that isn't set to auto-increment? That might be why the REPLACE command isn't working
精彩评论