Search code examples
javaandroidsqliteandroid-sqlite

SQLiteException: near "Ange": syntax error (code 1):


I wrote a method in DatabaseHelper class as below, it works for short lists but does not for long lists, I get the error Caused by: android.database.sqlite.SQLiteException: near "Ange": syntax error (code 1): , while compiling: SELECT genre FROM second WHERE name='L'Ange-Gardien and Notre-Dame de la Salette Police, Fire and EMS' I remove the item L'Ange-Gardien and Notre-Dame de la Salette Police, Fire and EMS but it still gives error.

    public String getScannerTypeByRadioName(String radioName) {
    String scannerType = null;
    myDataBase = this.getWritableDatabase();
    String query = "SELECT genre FROM second WHERE name='" + radioName + "'";
    Cursor c = myDataBase.rawQuery(query, null);
    while (c.moveToNext()) {
        scannerType = c.getString(c.getColumnIndex("genre"));
    }
    return scannerType;
}

Solution

  • Don't ever use concatenation of parameters that you want to pass in an sql statement.
    In this line:

    String query = "SELECT genre FROM second WHERE name='" + radioName + "'";
    

    you concatenate the string radioName with value:

    L'Ange-Gardien and Notre-Dame de la Salette Police, Fire and EMS
    

    which contains a single quote and this creates an invalid sql statement.
    Use the recommended way with ? placeholders:

    String query = "SELECT genre FROM second WHERE name=?";
    Cursor c = myDataBase.rawQuery(query, new String[] {radioName});