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
Release: 2024-11-17 20:50:02
Original
528 people have browsed it

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))
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template