You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for循环向SQLite3插入数据失败,报绑定数量错误

问题

我有一个包含999个播放列表的文件,每个播放列表包含多首歌曲。文件已被扁平化并转换为pandas DataFrame。我需要将所有数据存入SQLite3数据库,因此创建了如下数据库及表:

conn = sqlite3.connect('music.db')
cur = conn.cursor() 
cur.execute("""CREATE TABLE entries (
name text,
collaborative text,
end_date text,
pid integer,
modified_at integer,
num_tracks integer,
num_albums integer,
num_edits integer,
num_artists integer,
description text,
pos integer,
artist_name text,
track_uri text,
artist_uri text,
track_name text,
album_uri text,
album_name text
)""")

我需要用DataFrame中的数据填充该表,因此采用for循环结合executemany方法编写了插入代码:

for row in df.itertuples():
    cur.executemany("INSERT INTO entries VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17]])

运行后出现错误:

ProgrammingError: Incorrect number of bindings supplied. The current statement uses 17, and there are 9 supplied.

我确认字段数量为17,请问问题出在哪里?

解决方案

问题根源在于**executemany的使用方式错误**:

  • executemany要求第二个参数是包含多条记录的可迭代对象(比如[(记录1), (记录2), ...]),但你传入的是单条记录的列表。此时SQLite会把列表中的每个元素当作独立记录处理,若第一个元素(比如name字段值)是长度为9的字符串,就会被误认为是包含9个值的记录,从而触发绑定数量不匹配的错误。
  • 另外,循环遍历单条记录时,不需要用executemany,用execute即可。

提供三种修正方案,按推荐程度排序:

方案1:使用pandas自带的to_sql(最简便高效)

pandas内置了直接将DataFrame写入SQL数据库的方法,无需手动拼接SQL语句:

# if_exists参数可选'replace'/'append'/'fail',根据需求选择
df.to_sql('entries', conn, if_exists='append', index=False)
conn.commit()

方案2:用executemany批量插入(避免逐行循环)

将整个DataFrame转换为记录列表,一次性批量插入,效率比逐行循环高:

# 转换为不含索引的元组列表
records = [tuple(row) for row in df.to_numpy()]
cur.executemany("INSERT INTO entries VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", records)
conn.commit()

方案3:循环内改用execute插入单条记录

如果你坚持要逐行处理,把executemany换成execute即可:

for row in df.itertuples():
    cur.execute("INSERT INTO entries VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 
                (row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17]))
conn.commit()

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 07:09:15