Escaping % in MySQL Queries from Python
When crafting MySQL queries in Python, you may encounter scenarios where you need to avoid SQL injection or properly handle special characters like the percentage sign (%); otherwise, you might encounter errors. This article provides a solution to escape % characters in Python MySQL queries.
To resolve the "unsupported format character 'Y'" exception, you need to escape the percentage sign (%) in the query string. According to the MySQL documentation, literal escaping is recommended, achieved by replacing each % with a double percentage sign (%%).
Here's an updated code snippet that implements this approach:
query = """SELECT DATE_FORMAT(date_time,'%%Y-%%m') AS dd FROM some_table WHERE some_col = %s AND other_col = %s;""" cur.execute(query, (param1, param2))
By following this recommendation, MySQL will interpret %% as a literal percentage sign, preventing it from interfering with the query's formatting. This will resolve the exception you encountered and allow your query to execute successfully.
Das obige ist der detaillierte Inhalt vonWie entkomme ich %-Zeichen in MySQL-Abfragen von Python?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!