[英]Incorrect number of bindings in Python Sqlite3 executemany
所以我在 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])
我也尝试了最后一个命令的不同形式,但没有运气。 这是我在谷歌上找到的唯一方法。
您已经为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
是惯用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.