gpt4 book ai didi

python - 如何在sqlite中从此循环插入数据

转载 作者:行者123 更新时间:2023-12-03 08:20:01 24 4
gpt4 key购买 nike

我正在尝试从类似于此的循环中插入数据。

import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()

words = ["apple", "banana", "cherry"]
for word in words:
c.execute("insert into Words (word), values (?)",(word))
print(word)
conn.commit

c.close()
conn.close()

预期结果类似于:

我收到一个错误。但是我不确定如何正确格式化此代码。

错误:
Traceback (most recent call last):
File "file.py", line 7, in <module>
c.execute("insert into Words (word), values (?)",(word))
sqlite3.OperationalError: near ",": syntax error

最佳答案

错误的 list :
commit()不提交,因为它是一个方法
“不插入单词(单词)值(?)”,(单词),而不是“插入单词(单词),值(?)”,(单词)

正确的代码是:

import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()

words = ["apple", "banana", "cherry"]
for word in words:
c.execute("insert into Words (word) values (?)",(word,))
print(word)
conn.commit()
conn.close()

别担心,快乐的编码

关于python - 如何在sqlite中从此循环插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58900811/

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