python和mysql语句

python和mysql语句,python,Python,我正在尝试执行一个mysql查询,它需要包含%个字符。。。在构建查询时,我遇到了python使用%并试图将其作为变量的问题: statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) self.cursor.execute(statmt) 这自然会让人呕吐: statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl) TypeError: not enough argu

我正在尝试执行一个mysql查询,它需要包含%个字符。。。在构建查询时,我遇到了python使用%并试图将其作为变量的问题:

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
self.cursor.execute(statmt)
这自然会让人呕吐:

statmt="select id from %s WHERE `email` LIKE %blah%" % (tbl)
TypeError: not enough arguments for format string
我应该如何解决这个问题,以便Python停止将其作为变量读取,并将其作为字符串的一部分


谢谢

在Python格式化表达式中需要文本
%
时,请使用
%

statmt="select id from %s WHERE `email` LIKE '%%blah%%'" % (tbl)

有关详细信息,请参阅文档。

您不需要使用字符串插值。execute方法为您处理它,因此您可以改为执行以下操作:

statmt="select id from %s WHERE `email` LIKE %blah%"
self.cursor.execute(statmt, tbl)
您可以使用:


请确保您没有创建SQL注入漏洞。

您应该使用
%%


您可能应该使用
而不是字符串插值进行用户参数化查询。

现在,如果blah需要是“…即…”从tbl中选择id,其中
email
LIKE%%要在Python双引号字符串中转义文本
,请使用
\“
。或者,您可以使用三重引号字符串,
,在这里您可以“轻松地”引用“内容”
。如果我这样做…:statmt=“从%s中选择id,其中
电子邮件
类似%%\“%”%(tbl),我会收到一个错误:\u mysql\u异常。编程错误:(1064,'您的SQL语法有错误;请查看与您的MySQL服务器版本对应的手册,在第1行的\'%“%\'附近使用正确的语法。)MySQL可能仍然需要在字符串周围加上单引号,
比如“%\”%%
,而不仅仅是
比如%\“%
(我已经更新了答案以反映正确的MySQL用法).
statmt="select id from {tbl} WHERE `email` LIKE %blah%".format(tbl=tbl)