Escaping % from MySQL Queries in Python
Using the % character in MySQL queries can lead to exceptions if not escaped properly. For instance, the following query:
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))
will raise a "ValueError: unsupported format character 'Y'" exception because mysqldb interprets the % as a format specifier.
To resolve this issue, literal escaping is recommended by the mysqldb documentation. This involves doubling the % characters in the query string:
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))
This will prevent mysqldb from interpreting the % characters as format specifiers, allowing the query to execute successfully.
The above is the detailed content of How to Escape the % Character in MySQL Queries Using Python?. For more information, please follow other related articles on the PHP Chinese website!