miannelle
miannelle

Reputation: 2251

Android quotes within an sql query string

I want to perform a query like the following:

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 their input it crashes. If you change it to:

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

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

Upvotes: 45

Views: 41786

Answers (6)

Josef Pfleger
Josef Pfleger

Reputation: 74527

You should make use of the rawQuery method's selectionArgs parameter:

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

This not only solves your quotes problem but also mitigates SQL Injection.

Upvotes: 131

Absar Alam
Absar Alam

Reputation: 96

You should change

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

like

p_query = "select * from mytable where name_field = '" + android.database.DatabaseUtils.sqlEscapeString(uvalue)+ "'" ;

Upvotes: 5

Amt87
Amt87

Reputation: 5607

I prefer to escape Single quotes and Double quotes in each insert statement with Sqlite like this:

 String sqlite_stament = sqlite_stament.replace("'", "''").replace("\"", "\"\"");

Upvotes: 3

Nency
Nency

Reputation: 502

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

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

cool..!!

Upvotes: 1

gssi
gssi

Reputation: 5071

Have you tried replacing a single quote with 2 single quotes? That works for inputting data to a database.

Upvotes: 3

Nikhil
Nikhil

Reputation: 139

DatabaseUtils.sqlEscapeString worked properly for me. The string is enclosed by single quotes and the single quotes inside the string become double quotes. Tried using selectionArgs in the getContentResolver().query() but it didn't work at all.

Upvotes: 13

Related Questions