求助:Python用psycopg2插入PostgreSQL表时提示字符串格式化参数未完全转换
错误原因定位
- records数据结构完全不匹配接口要求。当前代码里的
consumer_list = [first_name, last_name, email, cell_phone, home_phone],列表里的每个元素都是pandas的Series列对象,整体是按“列维度”堆叠的结构;但psycopg2的executemany方法要求传入的records是按“行维度”组织的元组列表,每个元组对应一行待插入的、和SQL占位符一一对应的字段值,结构错位直接会触发参数数量校验失败的字符串格式化报错。 - INSERT语句的字段列表书写错误。代码里写的
INSERT INTO consumer (consumer_list)是把自定义的变量名当成了数据库表字段,实际的consumer表中根本不存在名为consumer_list的字段,正确的字段列表应该对应五个存储字段:first_name、last_name、email、cell_phone、home_phone。 - 参数匹配逻辑错位。当前SQL语句定义了5个
%s占位符,但传入的records是5个长度等于CSV数据行数的Series对象,psycopg2会把每个Series当成单条待处理记录,拆解后永远没法匹配上5个占位符的参数数量要求,最终抛出「未完全转换所有格式化参数」的报错。
修复方案
- 调整records的构造逻辑,把按列堆叠的Series转成按行打包的元组列表,匹配
executemany的入参要求。 - 修正INSERT语句中的字段列表,和实际的数据库表结构对齐。
核心修复代码如下:
# 前面读取CSV、拆分cell_phone/home_phone的处理逻辑保留不变 # 构造符合psycopg2要求的行级records结构 target_df = df[['first_name', 'last_name', 'email', 'cell_phone', 'home_phone']] records = [tuple(row) for row in target_df.to_records(index=False)] def bulkInsert(records): try: connection = psycopg2.connect(user="postgres", password="123", host="localhost", port="5432", database="Pharmacy") cursor = connection.cursor() # 修正字段列表,和实际表结构对齐 sql_insert_query = """ INSERT INTO consumer (first_name, last_name, email, cell_phone, home_phone) VALUES (%s,%s,%s,%s,%s) """ result = cursor.executemany(sql_insert_query, records) connection.commit() print(cursor.rowcount, "Record inserted successfully into consumer table") except (Exception, psycopg2.Error) as error: print("Failed inserting record into consumer table {}".format(error)) finally: if connection: cursor.close() connection.close() print("PostgreSQL connection is closed") bulkInsert(records)
更稳妥的批量插入替代方案
因为你本身已经用SQLAlchemy搭建过数据库连接,完全可以跳过手动拼接psycopg2语句的步骤,直接用pandas内置的to_sql方法完成批量写入,既不会出现参数错位问题,批量插入效率也更高:
from sqlalchemy import create_engine # 构建数据库连接引擎 engine = create_engine('postgresql+psycopg2://postgres:123@localhost:5432/Pharmacy') # 直接将处理好的DataFrame字段写入目标表,追加模式 target_df.to_sql(name='consumer', con=engine, if_exists='append', index=False)
内容的提问来源于stack exchange,提问作者Javier
相关产品推荐
相关产品推荐

