2

I am trying to execute a mysql query, which needs to contain % characters... While building the query, I run into a problem of python using % and trying to stick it as a variable:

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)

This naturally barfs with:

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string

How should I fix this so Python stops reading this as a variable, and takes it in as part of the string?

Thanks!

4 Answers 4

7

When needing a literal % inside a Python formatting expression, use %%:

statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)

See the documentation section 5.6.2. String Formatting Operations for more information.

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

4 Comments

Now, what if blah needed to be a "... ie.... SELECT id from tbl WHERE email LIKE %"%
To escape a literal " inside a Python double-quoted string, use \". Or, you can use triple-quoted strings, """where you can "quote" things easily""".
If I do that...: statmt="select id from %s WHERE email LIKE %%\"%%" % (tbl), I get an error:_mysql_exceptions.ProgrammingError: (1064, 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near \'%"%\' at line 1')
Well MySQL probably still requires single quotes around the string, LIKE '%%\"%%' and not just LIKE %%\"%% (I've updated my answer to reflect correct MySQL usage).
2

You don't need to use string interpolation. The execute method handles it for you, so you can do this instead:

statmt="select id from %s WHERE `email` LIKE %blah%"
self.cursor.execute(statmt, tbl)

Comments

2

you should escape your percent sign with %%

You should probably user parameterized queries though with ? and , instead of string interpolation.

Comments

1

You can use str.format:

statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl)

Make sure you're not creating a SQL injection vulnerability.

Comments

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.