SQLite使用executemany插入数据时报Error binding parameter 0错误怎么解决?
问题根源
你存在两个核心错误,共同导致了报错:
- 插入参数的结构构造错误
executemany要求传入的参数序列中,每个元素对应一条待插入记录,单条记录的参数是按SQL占位符顺序排列的值元组,不需要携带字段名。你当前构造的marketRecords是(字段名, 字段值)格式的元组列表,完全不符合参数要求。 - executemany入参格式错误
你在调用时给executemany传的第二个参数是[marketRecords],相当于把已经结构错误的参数又多套了一层列表,导致SQL的第一个占位符最终被绑定了('DateTime', str(dataframe['Timestamp']))这个元组,和表结构要求的TEXT类型不匹配,直接触发了unsupported type报错。
修复方案
第一步:修正插入参数的结构
不需要带字段名,按你INSERT语句中声明的字段顺序DateTime, Symbol_ID, Open, High, Low, Close, Volume排列值即可:
# 单条待插入记录的参数元组 single_record = ( str(dataframe['Timestamp']), int(symbolValue), float(dataframe['Open']), float(dataframe['High']), float(dataframe['Low']), float(dataframe['Close']), float(dataframe['Volume']) )
第二步:选择正确的执行方法
如果仅插入单条记录,直接用execute即可:
connection = sqlite3.connect(connectionString) with connection: connection.execute('''INSERT INTO Marketrecords (DateTime, Symbol_ID, Open, High, Low, Close, Volume) VALUES (?, ?, ?, ?, ?, ?, ?)''', single_record)
如果需要批量插入多条记录,再使用executemany,此时第二个参数是所有待插入记录的元组组成的列表:
# 多条记录的参数列表示例 multi_records = [ single_record_1, single_record_2, # 更多记录... ] with connection: connection.executemany('''INSERT INTO Marketrecords (DateTime, Symbol_ID, Open, High, Low, Close, Volume) VALUES (?, ?, ?, ?, ?, ?, ?)''', multi_records)
内容的提问来源于stack exchange,提问作者Mowgli
相关产品推荐
相关产品推荐

