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.
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.
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.
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.
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
.
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.
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)+ "'" ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With