I want to sanitise a UTF-8 encoded string before using it as part of a MySQL SELECT statement.
For example, I have:
query = MySQLdb.escape_string(query)
but this line is leading to a raised exception that reads
‘ascii’ codec can’t encode characters in position 0-2: ordinal not in
range(128).
How can I handle this?
Looks like MySQLdb is trying to encode your unicode query to a string. To do so it’s using the default encoding: ASCII.
Now, your input can’t be encoded into ASCII, so you just need to tell python what encoding it should use: utf-8.
You can achieve this by using
query = query.encode('utf-8').