Search code examples
androidsqliteinsertandroid-sqlite

Insert if not exists: SQLite


I want to insert data if that headline doesn't exist yet in the database.

This is the error I'm getting for the written query:

near "with": syntax error (code 1): , while compiling: SELECT * FROM movie WHERE headline=Albert Collen

Code:

public boolean Insert(Item item) {
    SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
    ContentValues contentValues = new ContentValues();
    Cursor cursor = sqLiteDatabase.rawQuery("SELECT * FROM " + TABLE + " WHERE headline=" + item.getName() , null);

    if (cursor.moveToFirst()) {
    } else {
        contentValues.put("name", item.getName());           
        long result = sqLiteDatabase.insert(TABLE, null, contentValues);

        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    cursor.close();
    sqLiteDatabase.close();

    return true;
}

Solution

  • You should use query parameters

    rawQuery("SELECT * FROM movie WHERE headline = ?", new String[] {"Albert Collen"});
    

    to avoid having to escape quotes and other chars.