Search code examples
androidmysqlsqlexception

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;
}

Solution

  • 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.