Escaping % in MySQL Queries from Python
When using Python's MySQLdb library, encountering a "ValueError: unsupported format character" exception while executing a query with a "%" character can be frustrating. This is because MySQL treats the "%" character as a wildcard and interprets it as part of the query instead of as a literal.
To resolve this issue, the documentation recommends escaping the literal "%" signs in the query string passed to execute(). By using a double % (%%), MySQL will recognize the "%" as a literal character rather than a wildcard.
For example, the query in the original question can be modified as follows:
query = """SELECT DATE_FORMAT(date_time, '%%Y-%%m') AS dd FROM some_table WHERE some_col = %s AND other_col = %s;""" cur.execute(query, (pram1, pram2))
By escaping the literal "%" signs, MySQL will now recognize "Y" and "m" as specific characters in the DATE_FORMAT string and the error will be avoided.
The above is the detailed content of How to Escape the '%' Character in MySQL Queries from Python?. For more information, please follow other related articles on the PHP Chinese website!