gpt4 book ai didi

python - MySQLdb executemany 使用列表作为输入?

转载 作者:太空狗 更新时间:2023-10-30 01:59:55 25 4
gpt4 key购买 nike

我想在我的程序中使用 executemany 一次存储 20 条记录,这是文档中的内容...

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 )
] )

但是,我在一个列表中有我的值,并且宁愿不使用列表中的索引来执行上述 18 个版本。

下面是我的代码...

db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [(str(keywords[0]), date, time, position[0])]
cursor.executemany(sql, params)
db.commit()

这很好用,它会提交列表中的第一个关键字,以及日期、时间和位置,我不想像下面那样重复参数 19 次...

db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])

]
cursor.executemany(sql, params)
db.commit()

以上是我试图避免的示例(我知道索引需要递增才能正常工作!;))

当我尝试将整个列表作为值传递时出现错误,我需要一次传递一个,有什么想法吗?可以执行很多吗,还是我应该循环并一次更新它们?但我很确定我试过了,但我遇到了类似的错误?不过我没有记下来。

最佳答案

params = [(str(keywords[i]), date, time, position[i]) for i in range(20)]

关于python - MySQLdb executemany 使用列表作为输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180335/

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