我知道executemany
可以用来方便地将新条目添加到数据库中;与for循环中的单个execute
相比,减少Python方法调用开销很有用。但是,我想知道这是否适用于SQLite的UPDATE
。
更具体地说,请考虑以下设置:
cnx = sqlite3.connect(DATABASE)
c = cnx.cursor()
for path in paths:
for data in some_computation(path):
c.execute("UPDATE TABLENAME SET cont=? WHERE id=?", (data[1], data[0]))
cnx.commit()
cnx.close()
我甚至不确定下面的方法是否会更快(必须对它进行基准测试),但问题是它不起作用,因为我做错了我假设。有关在下面的代码段中使用executemany
来完成我上面发布的任务的提示吗?
cnx = sqlite3.connect(DATABASE)
c = cnx.cursor()
for path in paths:
data_ids, data_conts = [], []
for data in some_computation(path):
if len(data_ids) >= CHUNKSIZE:
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", (data_conts, data_ids))
cnx.commit()
data_ids, data_conts = [], []
data_ids.append(data[0])
data_conts.append(data[1])
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", (data_conts, data_ids))
cnx.commit()
cnx.commit()
cnx.close()
非常感谢您的提示和见解!
编辑1:
底部示例的问题:
ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 50000 supplied.
(其中CHUNKSIZE = 50000)
编辑2:
发生同样的错误
cnx = sqlite3.connect(DATABASE)
c = cnx.cursor()
for path in paths:
data_conts = []
for data in some_computation(path):
if len(data_ids) >= CHUNKSIZE:
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", (data_conts,))
cnx.commit()
data_conts = []
data_conts.append([data[1], data[0]])
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", (data_conts,))
cnx.commit()
cnx.commit()
cnx.close()
但是感谢@falsetru我注意到了我的错误,它应该是
... WHERE id=?", data_conts)
而不是
... WHERE id=?", (data_conts,))
答案 0 :(得分:9)
您需要传递一系列序列([[cont,id], [cont,id], [cont,id], ...]
,而不是[cont, cont, cont, ...], [id, id, id, ..]
):
for path in paths:
params = []
for data in some_computation(path):
if len(data_ids) >= CHUNKSIZE:
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", params)
cnx.commit()
params = []
params.append([data[1], data[0]])
if params:
c.executemany("UPDATE TABLENAME SET cont=? WHERE id=?", params)
cnx.commit()
答案 1 :(得分:0)
你所拥有的是完美的,除了你应该使用zip(conts,id),其中conts和id是列表。这会自动为您重新排列。