Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android quotes within an sql query string

Tags:

android

sqlite

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.

like image 487
miannelle Avatar asked Aug 18 '09 20:08

miannelle


People also ask

How do I put quotes in a SQL string?

The apostrophe, or single quote, is a special character in SQL that specifies the beginning and end of string data. This means that to use it as part of your literal string data you need to escape the special character. With a single quote this is typically accomplished by doubling your quote.

Can I use quotes in SQL?

Single quotes are used to indicate the beginning and end of a string in SQL. Double quotes generally aren't used in SQL, but that can vary from database to database. Stick to using single quotes. That's the primary use anyway.

How do I use double quotes in a SQL string?

If you need to use single quotes and double quotes in a string that contains both a contraction and a quote, you will need to use the backslash '' to cancel out the following character.


3 Answers

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.

like image 150
Josef Pfleger Avatar answered Oct 27 '22 07:10

Josef Pfleger


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.

like image 39
Nikhil Avatar answered Oct 27 '22 07:10

Nikhil


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)+ "'" ;
like image 5
Absar Alam Avatar answered Oct 27 '22 06:10

Absar Alam