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

How to Escape the '%' Character in MySQL Queries from Python?

Mary-Kate Olsen
Release: 2024-11-16 03:28:03
Original
922 people have browsed it

How to Escape the '%' Character in MySQL Queries from Python?

Escaping % in MySQL Queries from Python

When using Python's MySQLdb library, encountering a "ValueError: unsupported format character" exception while executing a query with a "%" character can be frustrating. This is because MySQL treats the "%" character as a wildcard and interprets it as part of the query instead of as a literal.

To resolve this issue, the documentation recommends escaping the literal "%" signs in the query string passed to execute(). By using a double % (%%), MySQL will recognize the "%" as a literal character rather than a wildcard.

For example, the query in the original question can be modified as follows:

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

By escaping the literal "%" signs, MySQL will now recognize "Y" and "m" as specific characters in the DATE_FORMAT string and the error will be avoided.

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!

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