【问题标题】:How to perform '%' in my MySQL query如何在我的 MySQL 查询中执行“%”
【发布时间】:2016-02-02 01:24:55
【问题描述】:

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

下面是命令:

"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,结果看起来不错。

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    放两个 % 来逃避它。

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

    【讨论】:

    • 文件“/usr/lib/python2.6/site-packages/PyMySQL-0.6.6-py2.6.egg/pymysql/cursors.py”,第 134 行,在 mogrify 中查询 = 查询% self._escape_args(args, conn) 这行会导致错误,因为它使用python字符串格式替换你在sql中的参数。
    • 有效!但为什么?一种逃避方式?我打印了'sql',它显示 %% double %
    • 拯救了我的一天。 single % 在本地运行良好,但部署到服务器时会抛出异常。我不知道为什么,但它适用于 python fastapi 。谢谢。
    猜你喜欢
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2021-09-11
    • 2017-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多