gpt4 book ai didi

python - 类型错误 : not all arguments converted during string formatting

转载 作者:IT老高 更新时间:2023-10-29 00:20:18 25 4
gpt4 key购买 nike

我在将 CSV 文件加载到 mysql 数据库时遇到了一些问题。这是我的代码:

for q in csvReader:
name, price, LastUpdate, today = q
co.execute("""INSERT INTO fundata (name, price, LastUpdate) VALUES(name, price, LastUpdate);""",q)

我收到一条错误消息:TypeError: not all arguments converted during string formatting。

名称列是一个字符串,价格是一个 float ,LastUpdate 是一个日期。我读了一点,看到一些脚本将值包装在 %(value)s 和 %(value)d 中(在我的例子中,我使用 f 而不是 d),但后来我得到了一个不同的错误:

类型错误:格式需要映射

谁能帮我看看我做错了什么?

谢谢!

最佳答案

如果我没记错的话,您应该在查询中使用 %s 和 MySQLdb 来表示您希望参数元组元素被格式化的位置。这与大多数其他实现中使用的常用 ? 占位符不同。

for q in csvReader:
name, price, LastUpdate, today = q
co.execute("INSERT INTO fundata (name, price, LastUpdate) VALUES(%s, %s, %s);",q)

编辑:这也是一次插入多行的示例,这比逐一插入更有效。来自 MySQLdb User's Guide :

c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
] )

Here we are inserting three rows of five values. Notice that there is a mix of types (strings, ints, floats) though we still only use %s. And also note that we only included format strings for one row. MySQLdb picks those out and duplicates them for each row.

关于python - 类型错误 : not all arguments converted during string formatting,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5277679/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com