Skip to content Skip to sidebar Skip to footer

Android Sqlite Insert Record If Not Exists

I want to add a new item (Cheese) to an sqlite table but only in case it does not exist. I have two columns only in the table: _id (KEY_ROWID_PR) and product_name (KEY_NAME_PR). I'

Solution 1:

I think you may need single quotes around the variable item whenever it appears because it a value not a column name. Try this code:

publicvoid populate_base_lists2(String tablename, String item) {
ourDatabase.execSQL("INSERT INTO " + tablename +
" (" + KEY_NAME_PR + ") SELECT * FROM (SELECT '" + item  + "')
WHERE NOT EXISTS (
SELECT " + KEY_NAME_PR +
" FROM " + tablename + " WHERE " + KEY_NAME_PR + " = '" + item + "'
) LIMIT 1;");
}

Hope that helps.

Post a Comment for "Android Sqlite Insert Record If Not Exists"