如何在我的MySQL查询中执行'%'

时间:2015-11-02 07:52:12

标签: python mysql

我使用https://github.com/PyMySQL/PyMySQL连接MySQL。我想在MySQL命令中执行“喜欢”查询。

以下是命令:

"select * from table where c1 > '2015-11-01' and c2 not like '%word%'"

我有一个表table,其中包含列c1,c2和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)

它将返回此错误:

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

我认为问题来自not like '%word%'。我该如何解决这种错误?我直接打印了SQL,结果看起来不错。

1 个答案:

答案 0 :(得分:2)

放两%以逃避它。

"select c3 from table where c1 > %s and c2 not like '%%word%%'"