Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape special characters like ' in sqlite in android

I have a function which is executing a query on a table in SQLite database. I declare a constant: public static final String CANADA_HISTORY = "Canada's History";. This is stored in a String variable let's say difficulty,

I have one query:

Cursor c = mDb.rawQuery("select * from Questions_answers where CHAPTERS = '"+difficulty+"'" , null); 

It is throwing an exception near the apostrophe.

Logcat output:

I/Database( 1170): sqlite returned: error code = 1, msg = near "s": syntax error D/AndroidRuntime( 1170): Shutting down VM W/dalvikvm( 1170): threadid=1: thread exiting with uncaught exception (group=0x40015560) E/AndroidRuntime( 1170): FATAL EXCEPTION: main E/AndroidRuntime( 1170): android.database.sqlite.SQLiteException: near "s": syntax error: , while compiling: select * from Questions_answers where CHAPTERS  = 'Canada's History' 

I have also tried:

1.  difficulty=difficulty.replaceAll("'","''"); 2.  difficulty=difficulty.replaceAll("'","\'"); 3.  difficulty = DatabaseUtils.sqlEscapeString(difficulty); 

To add to that, it's working me for the single words like Canada History, I mean without the special character word.

Please give me advice for the solve problem Thanks.

like image 863
Rahul Patel Avatar asked Sep 27 '12 06:09

Rahul Patel


People also ask

How do I escape in SQLite?

Double-quotes in SQLite identifiers are escaped as two double quotes. SQLite identifiers preserve case, but they are case-insensitive towards ASCII letters. It is possible to enable unicode-aware case-insensitivity.

How do I escape a special character in SQL?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.


2 Answers

The SQL standard specifies that single-quotes in strings are escaped by putting two single quotes in a row. SQL works like the Pascal programming language in the regard. SQLite follows this standard. Example:

INSERT INTO xyz VALUES('5 O''clock'); 

Ref : SQLite FAQ

like image 89
Pankaj Kumar Avatar answered Sep 22 '22 06:09

Pankaj Kumar


The best way is to use a native Android method designed for exactly this purpose:

DatabaseUtils.sqlEscapeString(String) 

Here is the documentation for it online:

  • sqlEscapeString() on Android Developers

The main advantage of using this method, in my opinion, is the self-documentation because of the clear method name.

like image 37
Richard Le Mesurier Avatar answered Sep 21 '22 06:09

Richard Le Mesurier