[英]How do I get a literal '%' in a mysql connector python query?
Consider this code:考虑这个代码:
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")
where app.sql
is a reference to the connection object.其中
app.sql
是对连接对象的引用。
I would like it to execute something similiar to: select username, fname, bio from followers where username like %j% limit 10 offset 0
but instead it always gives me the error:我希望它执行类似于以下内容的操作:
select username, fname, bio from followers where username like %j% limit 10 offset 0
但它总是给我错误:
File "/---/user.py", line 67, in search
csr.execute("select username, fname, avatarUrl, bio from followers where username like %%%s%% limit %d offset %d", (searchstr, limit, 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
I can't figure out what I am doing wrong because我无法弄清楚我做错了什么,因为
>>> "%%%s%% %d %d" % ("j", 10, 0)
"%j% 10 0"
which is the expected output.这是预期的输出。 How can I fix this?
我怎样才能解决这个问题?
Placeholders do not work like copy and paste, you can't just place them anywhere and expect them to be understood.占位符不像复制和粘贴那样工作,你不能把它们放在任何地方并期望它们被理解。 Even if it did work like that, in your case you'd end up with
like %foo%
, which is invalid SQL syntax.即使它确实像那样工作,在你的情况下你最终会
like %foo%
,这是无效的 SQL 语法。
You need to put one string placeholder into the query, and provide a string as argument which contains the LIKE
wildcards:您需要将一个字符串占位符放入查询中,并提供一个字符串作为包含
LIKE
通配符的参数:
csr.execute('... LIKE %s ...', (f'%{searchstr}%', ...))
In other words, you supply the %
wildcards from Python, not from within the SQL statement.换句话说,您从 Python 中提供
%
通配符,而不是从 SQL 语句中提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.