如何在mysql连接器python查询中获取文字'%'?

问题描述

考虑以下代码

def search(searchstr: str,limit: int=10,offset: int=0):
    csr = app.sql.cursor(dictionary=True)
    csr.execute("select username,fname,bio from followers where username like %%%s%% limit %d offset %d",(searchstr,limit,offset))
    return csr.fetchall()

search("j")

其中app.sql是对连接对象的引用。

我希望它执行类似的操作: select username,bio from followers where username like %j% limit 10 offset 0 但是它总是给我错误

  File "/---/user.py",line 67,in search
    csr.execute("select username,avatarUrl,offset))
  File "/---/venv/lib/python3.8/site-packages/MysqL/connector/cursor.py",line 542,in execute
    raise errors.ProgrammingError(
MysqL.connector.errors.ProgrammingError: Not all parameters were used in the sql statement

我不知道自己在做什么错,因为

>>> "%%%s%% %d %d" % ("j",10,0)
"%j% 10 0"

这是预期的输出。我该如何解决

解决方法

占位符不能像复制和粘贴那样工作,您不能仅将它们放置在任何地方并期望它们被理解。即使这样做确实可行,但在您的情况下,您最终还是使用like %foo%,这是无效的SQL语法。

您需要在查询中放入一个字符串占位符,并提供一个包含LIKE通配符的字符串作为参数:

csr.execute('... LIKE %s ...',(f'%{searchstr}%',...))

换句话说,您从Python提供%通配符,而不是从SQL语句中提供通配符。