gpt4 book ai didi

python - 通过python循环的SQL插入查询

转载 作者:行者123 更新时间:2023-12-03 18:04:00 25 4
gpt4 key购买 nike

我正在尝试使用以下代码在python中使用for循环将多行插入表中:

ID = 0
values = ['a', 'b', 'c']
for x in values:
database.execute("INSERT INTO table (ID, value) VALUES (:ID, :value)",
ID = ID, value = x)
ID += 1

我预期会发生的是,这段代码会在我的表中插入三行。唯一的问题是它只执行一次查询。所以我只会得到行“0,'a'”。

没有弹出任何错误消息,它只是没有用其他两个值更新表。然而,奇怪的是,我可以通过使用多个查询来规避这个问题,如下所示:
ID = 0
values = ['a', 'b', 'c']
for x in values:
database.execute("INSERT INTO table (ID) VALUES (:ID)", ID = ID)
database.execute("INSERT INTO table (value) VALUES (:value)", value = x)
ID += 1

虽然这会更新我的代码,但当我在表中进一步添加列时,此方法会变得更加乏味。有谁知道为什么第一段代码不起作用而第二段代码起作用?

最佳答案

execute method将数组作为第二个参数。

execute(sql[, parameters])

Executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).



这应该有效:
database.execute("INSERT INTO table (ID, value) VALUES (:ID, :value)", [ID , x])
您可能想调查 executemany当你在文档中时。

来自同一个文档:

commit()

This method commits the current transaction. If you don’t call this method, anything you did since the last call to commit() is not visible from other database connections. If you wonder why you don’t see the data you’ve written to the database, please check you didn’t forget to call this method.



您可能想调查 executemany当你在文档中时。

关于python - 通过python循环的SQL插入查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392362/

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