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

标签 python syntax-error operationalerror

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

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/

相关文章:

python - Django - 模型字段的动态唯一测试

c++ - 最大的除数程序无法正常工作

json - 无法在字符串内过滤值

django.db.utils.OperationalError : fe_sendauth: no password supplied

python - Windows 10 python 3 中的 Twisted 构建轮子失败

python - 如何在用户注册时生成一个魔数(Magic Number)并将其填充到数据库中?

mysql - codeigniter 生成的更新中的语法错误

mysql - python : sqlalchemy - how do I ensure connection not stale using new event system

python - 使用 Python 对 C 代码进行单元测试的最简单方法