如何批量插入多行数据到SQLite3数据库?遇绑定数量错误求助
问题分析与解决
错误原因
你遇到的sqlite3.ProgrammingError是因为传入executemany的数据结构不正确:
cursor.fetchall()返回的已经是包含元组的列表,比如[(120, '21-08-2022', '1112', 'Alfa Romeo', 'james'), ...],这正是executemany需要的格式。- 但你用
self.tenlistchecks.append(...)把这个列表又嵌套了一层,变成了[[(元组1), (元组2), ...]],导致executemany把外层列表的第一个元素(也就是整个查询结果列表)当作单条数据处理,这条数据只有1个元素,和SQL语句要求的5个绑定值不匹配,从而报错。
修正后的代码
def paid_or_returned_buyingchecks(self): date = datetime.now() now = date.strftime('%Y-%m-%d') self.con = sqlite3.connect('car dealership.db') self.cursorObj = self.con.cursor() # 查询数据,直接获取符合格式的结果 self.cursorObj.execute("select id, paymentdate , paymentvalue, car ,sellername from cars_buying_checks where nexttendays=?",(now,)) dashboard_buying_checks_dates_output = self.cursorObj.fetchall() # 直接将fetchall返回的列表传入executemany,无需额外嵌套 if dashboard_buying_checks_dates_output: # 可选:避免空列表插入 self.cursorObj.executemany("insert into paid_buying_checks VALUES(?,?,?,?,?)", dashboard_buying_checks_dates_output) self.con.commit() self.con.close() # 建议:操作完成后关闭连接
关键修改点
- 移除了多余的
self.tenlistchecks.append(...),直接使用fetchall()返回的列表作为executemany的参数。 - 增加了空列表判断,避免当没有查询结果时执行无效的插入操作。
- 补充了数据库连接关闭的代码,防止资源泄漏。
内容的提问来源于stack exchange,提问作者asaad kittaneh
相关产品推荐
相关产品推荐

