您可能以前见过它,但我基本上是在尝试避免 MySQL 注入(inject),因此我使用 Python 格式化查询,如下所示:
if "username" in form:
username = form["username"].value
else:
success = 0
error = "User Name is Missing"
cur.execute("SELECT COUNT(*) FROM users WHERE screenName=':1'",[username])
results = int(cur.fetchall()[0][0])
这会引发错误:
<type 'exceptions.TypeError'>: not all arguments converted during string formatting
args = ('not all arguments converted during string formatting',)
message = 'not all arguments converted during string formatting'
知道出了什么问题吗? 谢谢
最佳答案
您没有指定您正在使用的确切库,但假设它符合 Python DB API,您可能需要将 execute
行更改为:
cur.execute("SELECT COUNT(*) FROM users WHERE screenName=%s",[username])
编辑以回应OP的评论:
使用 %s
是防止 SQL 注入(inject)的当前标准。我不确定您链接的答案中的帖子在那里得到了什么...需要记住的几件事是该线程已被关闭为“没有建设性”,并且该答案也是〜7年旧的,所以很可能当时存在一些问题,该答案可能引用了不再适用的问题。
但是%s
意味着库(在execute
方法中)处理所有转义和引用,并且是防止注入(inject)的方法。 (与使用常规插值相反,例如通过 format
进行插值,这会使其暴露于注入(inject)。)
请注意,非常具体不是 '%s'
,然后在 execute
中使用 foo % bar
调用,但不带引号的 %s
并将参数作为第二个参数传递给 execute
。
例如,我使用psycopg2,它完全DB API兼容,其current doc描述了使用 %s
来防止注入(inject)。
关于python - 类型错误 : not all arguments converted during string formatting string python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29270596/