Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Exception (unrecognized token) when string contains quotes

I'm getting SQL Exception (unrecognized token) when I use my function to retrieve data from "mysql.db". The exception occurs when String address has quotes inside.

I already tried to change this line

KEY_ADDRESS + "='" + address + "'",

to

KEY_ADDRESS + "=\"" + address + "\"",

It solves my problem for strings containing single quote (') and (`), but creates another problem for strings containing double quotes (").

I tried using

DatabaseUtils.sqlEscapeString(address);

with no effect.

I tried to use escape function from this question: How do I escape special characters in MySQL?, but it did not work.

This is my code:

public Cursor getNameFromAddress(String address) throws SQLException
{
    Cursor mCursor =
            db.query(DATABASE_TABLE_PRINC, new String[] {
                    KEY_ROWID,
                    KEY_NAME,
                    KEY_ADDRESS
                    },
                    KEY_ADDRESS + "='" + address + "'",
                    null,
                    null,
                    null,
                    null,
                    null);
    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;
}
like image 453
Daniel Avatar asked May 19 '26 22:05

Daniel


1 Answers

Those selectionArgs / whereArgs are intended to be used for that:

Cursor mCursor =
        db.query(DATABASE_TABLE_PRINC, new String[] {
                KEY_ROWID,
                KEY_NAME,
                KEY_ADDRESS
                },
                KEY_ADDRESS + "=?",
                new String[] { address },
                null,
                null,
                null,
                null);

replace all "='" + stuff + "'" with "=?" and put the data to fill the ?s in the order they have to be filled in a String[]

? will then automatically be replaced by escaped String data.

like image 198
zapl Avatar answered May 22 '26 10:05

zapl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!