Escaping % in MySQL Queries from Python
When executing a MySQL query that includes a % character in Python, you may encounter an error due to its special significance as a format specifier. To prevent this, you need to escape the % character to indicate that it should be treated as a literal.
Solution: Literal Escaping
The recommended approach to escaping % is using literal escaping as described in the MySQL documentation. This involves doubling the % character, i.e. replacing % with %%.
For example, consider the following query:
query = """SELECT DATE_FORMAT(date_time,'%%Y-%%m') AS dd FROM some_table WHERE some_col = %s AND other_col = %s;"""
By escaping the % characters in the date format string, we effectively tell MySQL to ignore them and treat them as literal characters. When you execute this query, it will produce the desired results without triggering the format specifier error.
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!