【问题标题】:How can I insert data from this loop in sqlite如何在 sqlite 中从此循环中插入数据
【发布时间】:2019-11-17 13:15:33
【问题描述】:

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

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

【问题讨论】:

    标签: python syntax-error operationalerror


    【解决方案1】:

    错误列表: commit() 不提交,因为它是一种方法 "insert into Words (word) values (?)",(word,) 不是 "insert into Words (word), values (?)",(word)

    正确的代码是:

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

    别担心,愉快的编码

    【讨论】:

      【解决方案2】:

      我猜您遇到了错误,因为您不能将单个项目放在括号中以使其成为元组 - 所以 (word) 不是要走的路。它应该是其中之一(无论哪个对您来说更易读):

      c.execute("insert into Words (word) values (?)",(word,))
      

      注意word 后面插入的逗号使其成为一个元组。或者:

      c.execute("insert into Words (word) values (?)",[word])
      

      这将使word 成为list 中的唯一元素

      您可以在控制台中亲眼看到,执行('hello') 之类的操作不等于('hello',)。第一个仍然是一个字符串,第二个是一个元组(这是您的命令所需要的)。

      编辑:另外,您在该命令中有一个不应该存在的逗号

      【讨论】:

      • c.execute("insert into Words (word), values (?)",(word,)) sqlite3.OperationalError: near ",": syntax errorclass="comcopy">仍然出现同样的错误跨度>
      • @ned 抱歉,我编辑了那个,不需要逗号,用更新后的代码重试
      【解决方案3】:

      最简单的方法是使用f-string:

      c.execute(f"INSERT INTO Words (word), values ({word})")

      这更容易阅读 :) 但需要 python 3.6+

      import sqlite3
      
      with sqlite3.connect('database.db') as conn:
          c = conn.cursor()
      
          words = ["apple", "banana", "cherry"]
          for word in words:
               c.execute(f"INSERT INTO Words (word), values ({word})")
               print(word) 
               conn.commit()
      

      【讨论】:

      • 这会起作用,但根据我的经验,在 sqlite 命令上使用 f-stings 是一个非常糟糕的主意(更不用说对于大量值来说真的很难)
      • 不是我尝试过的,因为它使 SQL 代码看起来像 SQL。所有 ? ? ?很容易混淆。
      猜你喜欢
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      • 2021-07-02
      • 2017-03-13
      • 2013-11-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      相关资源
      最近更新 更多