35

How do I escape the % from a mysql query in python.

For example

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))

gives me a "ValueError: unsupported format character 'Y'" exception.

How do I get mysqldb to ignore the %? Can't see this in any of the docs.

Daniel
  • 839
  • 2
  • 11
  • 14
  • 2
    +1 SO just surprises me. I come here thinking man this is going to be a hard one to phrase! But no, it's already been asked and answered! – Karthic Raghupathi Nov 01 '13 at 23:41

1 Answers1

45

Literal escaping is recommended by the docs:

Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293