【问题标题】:TypeError: not all arguments converted during string formatting string pythonTypeError:在字符串格式化字符串python期间并非所有参数都转换
【发布时间】:2015-03-26 03:28:19
【问题描述】:

您可能以前见过它,但我基本上是在尝试避免 MySQL 注入,所以我使用 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 mysql


    【解决方案1】:

    您没有指定您正在使用的确切库,但假设它与 Python DB API 兼容,您可能希望将 execute 行更改为:

    cur.execute("SELECT COUNT(*) FROM users WHERE screenName=%s",[username])
    

    根据 OP 的评论进行编辑:

    使用%s 是当前防止SQL 注入 的标准。我不确定您链接的答案中的帖子是什么......需要记住的几件事是该线程已被关闭为“不具建设性”,而该答案也是〜7年旧的,因此很可能当时存在问题,该答案可能已引用不再适用。

    %s 表示库(在execute 方法中)处理所有转义和引用,是防止注入的方法。 (与使用常规插值相反,比如通过format,这会使其暴露于注入。)

    请注意,不是 '%s' 然后在execute 调用中使用foo % bar,而是一个未引用的%s 并将参数作为第二个参数传递给execute .

    例如,我使用 psycopg2,它完全符合 DB API,它的 current doc 描述了使用 %s 来防止注入。

    【讨论】:

    猜你喜欢
    • 2015-10-28
    • 2013-10-21
    • 1970-01-01
    • 2017-08-13
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多