Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python, % and mysql statements

Tags:

python

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!

like image 918
Cmag Avatar asked Dec 19 '25 17:12

Cmag


2 Answers

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.

like image 73
Greg Hewgill Avatar answered Dec 21 '25 06:12

Greg Hewgill


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)
like image 31
highlycaffeinated Avatar answered Dec 21 '25 07:12

highlycaffeinated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!