Android quotes in sql query string

I want to execute the following query:

uvalue = EditText( some user value ); p_query = "select * from mytable where name_field = '" + uvalue + "'" ; mDb.rawQuery( p_query, null ); 

if the user enters a single quote in his input, it is reset. If you change it to:

 p_query = "select * from mytable where name_field = \"" + uvalue + "\"" ; 

it crashes if the user enters a double quote in his input. and, of course, they could always enter single and double quotes.

+41
android sqlite
Aug 18 '09 at 20:05
source share
6 answers

You should use the rawQuery selectionArgs parameter:

 p_query = "select * from mytable where name_field = ?"; mDb.rawQuery(p_query, new String[] { uvalue }); 

This not only solves your problem with quotes, but also softens SQL Injection .

+125
Aug 18 '09 at 20:51
source share

DatabaseUtils.sqlEscapeString is working correctly for me. The string is enclosed in single quotes, and the single quotes within the string become double quotes. Tried to use selectionArgs in getContentResolver (). Query (), but it didn't work at all.

+14
Apr 16 '10 at 12:40
source share

Have you tried replacing one quotation mark with two single quotation marks? This works for entering data into a database.

+1
Jul 20 2018-11-21T00:
source share

I prefer to avoid single quotes and double quotes in each insert statement using Sqlite as follows:

  String sqlite_stament = sqlite_stament.replace("'", "''").replace("\"", "\"\""); 
+1
Apr 09 '14 at 15:48
source share

You have to change

 p_query = "select * from mytable where name_field = '" + uvalue + "'" ; 

like

 p_query = "select * from mytable where name_field = '" + android.database.DatabaseUtils.sqlEscapeString(uvalue)+ "'" ; 
+1
Jan 30 '17 at 14:01
source share

I have the same problem, but now it is solved simply by writing code, as in your case you want to insert a uvalue value. Then write how

 uvalue= EditText( some user value ); uvalue = uvalue.replaceAll("'", "''"); p_query = "select * from mytable where name_field = '" + uvalue + "'" ; mDb.rawQuery( p_query, null ); 

cool..!!

0
Oct 19
source share



All Articles