Home >Database >Mysql Tutorial >How to Escape the % Character in MySQL Queries Using Python?

How to Escape the % Character in MySQL Queries Using Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-17 20:50:02527browse

How to Escape the % Character in MySQL Queries Using Python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn