Reputation: 17
I use https://github.com/PyMySQL/PyMySQL to connect with MySQL. I want to perform a "like" query in a MySQL command.
Below is the command:
"select * from table where c1 > '2015-11-01' and c2 not like '%word%'"
I have a table table
which has columns c1, c2, and c3.
import pymysql.cursors
def query_my(my_query):
connection = pymysql.connect(host='',
user='',
passwd='',
db='',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
sql = "select c3 from table where c1 > %s and c2 not like '%word%'"
cursor.execute(sql, (my_query))
re = cursor.fetchall()
return re
connection.commit()
finally:
connection.close()
my_query='2015-11-01'
query_my(my_query)
and it will return this error:
Traceback (most recent call last):
File "/home/y/share/htdocs/cgi/weekly_report_v2.py", line 31, in <modul
print query_inc_group(i_start,i_stop)
File "/home/y/share/htdocs/cgi/weekly_report_v2.py", line 18, in query_inc_group
cursor.execute(sql, (_i_start,_i_stop))
File "/usr/lib/python2.6/site-packages/PyMySQL-0.6.6-py2.6.egg/pymysql/cursors.py", line 143, in execute
query = self.mogrify(query, args)
File "/usr/lib/python2.6/site-packages/PyMySQL-0.6.6-py2.6.egg/pymysql/cursors.py", line 134, in mogrify
query = query % self._escape_args(args, conn)
TypeError: not enough arguments for format string
I think the problem is from not like '%word%'
. How do I fix this kind of error? I have printed SQL directly, and the result looks good.
Upvotes: 0
Views: 1351
Reputation: 21883
Put two % to escape it.
"select c3 from table where c1 > %s and c2 not like '%%word%%'"
Upvotes: 4