11

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

1 Answer 1

25

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Escaping with %% works, thanks :) Use of literal strings gave the same error.
@user984003 strange, but i can't even test it right now. glad it helped anyway.
@soulcheck: String syntax has nothing to do with interpretation of % (unlike how Bourne Shell or Ruby interpret $, for example). So """%start%""" is the exact same as "%start%", which is the same as '%start%' and r'%start%', etc.
Passing the parameters didn't work. I don't get an error, but it finds 0 lines, making me think that it's not seeing the wildcards. This worked: sql = "select text from cmt_steps where text like '%%"+start+"%%'"
The string syntax made the difference: """SELECT * FROM courses WHERE title like %s""" works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.