【问题标题】:Incorrect number of bindings in Python Sqlite3 executemanyPython Sqlite3 executemany 中的绑定数量不正确
【发布时间】:2020-06-20 18:57:06
【问题描述】:

所以我在 Python 中有一个 sqlite3 数据库,其中有一个表,我试图向其中添加 1000 个字符串。问题是,当我使用 executemany 命令时出现错误

sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用 1,提供了 1000 个。

这是我的代码简化:

db = sqlite3.connect("service.db")
db.isolation_level = None
c = db.cursor()

c.execute("CREATE TABLE Places (id INTEGER PRIMARY KEY, name TEXT)")

toBeAdded = [0]*1000
i = 0
while i < 1000:
    toBeAdded[i] = ("P"+str(i+1))
    i += 1

c.executemany("INSERT INTO Places(name) VALUES (?)",[toBeAdded])

我也尝试了最后一个命令的不同形式,但没有运气。这是我在 Google 上找到的唯一方法。

【问题讨论】:

    标签: python sqlite executemany


    【解决方案1】:

    您已向executemany 提供了一个平面列表。相反,该方法需要一个嵌套结构,每个内部序列代表一组要添加到查询的参数。

    所以,您希望 ['P0', 'P1', 'P2', ...] 成为 [['P0'], ['P1'], ['P2'], ...]。您可以通过在创建列表时添加方括号来解决此问题,使其嵌套:

    toBeAdded = [0]*1000
    i = 0
    while i < 1000:
        toBeAdded[i] = [("P"+str(i+1))] # Note the surrounding square brackets
        i += 1
    

    其他反馈

    生成数据的更好方法是使用 for 循环并摆脱 while 循环 - 您有预先确定的迭代次数要执行,因此使用 for 是惯用的.您也不需要事先初始化列表。

    to_be_added = []
    for i in range(1000):
        to_be_added.append([("P"+str(i+1))])
    

    或者,使用 列表推导

    to_be_added = [[("P"+str(x+1))] for x in range(1000)]
    

    你会注意到我已经从变量名中删除了驼峰式;这符合 Python 风格指南 - PEP8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2015-12-06
      • 2013-10-28
      • 2021-06-28
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      相关资源
      最近更新 更多