Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape % from python mysql query

Tags:

python

mysql

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.

like image 220
Daniel Avatar asked Jun 14 '10 13:06

Daniel


People also ask

How do you escape a string in Python?

1. Escape sequence in python using strings. In Python strings, the backslash “ ” is a special character, also called the “escape” character. It is used in representing certain whitespace characters: “\t” is a tab, “\n” is a new line, and “\r” is a carriage return.

Which character is the escape character for MySQL?

MySQL recognizes the following escape sequences. \0 An ASCII NUL (0x00) character. \' A single quote (“'”) character. \" A double quote (“"”) character.

How do I escape the backslash in MySQL?

\ functions as an escape character in LIKE by default. From the manual for LIKE : Because MySQL uses C escape syntax in strings (for example, “\n” to represent a newline character), you must double any “\” that you use in LIKE strings.


1 Answers

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. %%.

like image 66
SilentGhost Avatar answered Oct 07 '22 23:10

SilentGhost