Search code examples
androidsqlitecursorsqliteopenhelper

sqlite.SQLiteException: near "s": syntax error: because of apostrophe


The song name that I want to insert it into my table contains a " ' " (apostrophe )so , there is an error when the request is excuted. How can I fix it

Cursor pid = mDB.rawQuery("select Id  FROM MusicPlayer WHERE "Path ='" + sname + "';", null);

I am getting sname runtime so .. sname=/mnt/sdcard/Now Thats What I Call Music 85 [Bubanee]/16 - Let's Get Ready To Rhumble (100% Radio Mix) - PJ & Duncan.mp3

I get below error..

android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling: SELECT Id FROM MusicPlayer WHERE Path ='/mnt/sdcard/Now Thats What I Call Music 85 [Bubanee]/16 - Let's Get Ready To Rhumble (100% Radio Mix) - PJ & Duncan.mp3';

Because sname contain let's word with ' which gives me error.


Solution

  • In theory you could escape ' as '' in SQL.

    However, it's better to use variable binding. Replace the string literals in SQL with ? and supply corresponding number of Strings in an array:

    Cursor pid = mDB.rawQuery("select Id  FROM MusicPlayer WHERE Path = ?;",
        new String[] { sname });