Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Python LIKE wildcard

Tags:

python

mysql

I want to do a Python MySQL query such as:

cursor = connection.cursor()
sql = "select text \
       from steps \
       where text like '%start%'"
cursor.execute(sql)

But the % isn't seen as a wildcard, it's expecting a variable, I guess. I get an error:

TypeError: not enough arguments for format string

Nothing seems to work. It would also be nice if I could use a variable instead of '%start%'

like image 237
user984003 Avatar asked Jan 08 '12 04:01

user984003


1 Answers

I assume you're using python db-api.

You can try escaping % as %%.

As for passing the parameters there is a number of ways, for example:

cursor = connection.cursor()
sql = """select text 
   from steps 
   where text like %s"""
cursor.execute(sql, (('%' + 'start' + '%',))

You can see examples of the other ways of parameter passing on this blog in "Interface modułu" section. Not all of them work with all connectors.

like image 110
soulcheck Avatar answered Sep 25 '22 02:09

soulcheck