【问题标题】:python postgresql TypeError: not all arguments converted during string formatting [duplicate]python postgresql TypeError:字符串格式化期间并非所有参数都转换[重复]
【发布时间】:2021-08-09 08:33:11
【问题描述】:

“INSERT into route_list VALUES ('0.0.0.0/0')”命令可以正常工作。但是循环不起作用。这个错误是什么意思?又该如何摆脱她?

data = ['0.0.0.0/0']

for d in data:

  cursor.execute("INSERT into route_list VALUES %s", d)

TypeError:字符串格式化期间并非所有参数都转换

【问题讨论】:

    标签: python postgresql typeerror


    【解决方案1】:

    使用这个:

    cursor.execute("INSERT into route_list VALUES (%s)", [d])
    or
    cursor.execute("INSERT into route_list VALUES (%s)", (d,))
    or
    cursor.execute("INSERT into route_list VALUES ('{0}')".format(d))
    

    【讨论】:

    • 请不要。使用docs 中描述的参数替换。对查询值使用字符串格式是error-prone and invites SQL injection attacks
    • @snakecharmerb 使用 format() 有什么问题。 This 与 format() 无关
    • @pgyogesh 使用格式(或 f-strings)引发与使用 %-interpolation 或字符串连接完全相同的问题:开发人员必须确保每次都正确引用变量,否则可能会引入错误或漏洞。当所有 DB-API 库都免费提供时,这没有任何借口。
    猜你喜欢
    • 1970-01-01
    • 2015-10-28
    • 2013-10-21
    • 1970-01-01
    • 2017-01-18
    • 2022-07-24
    • 2017-08-13
    • 2020-11-11
    • 1970-01-01
    相关资源
    最近更新 更多