使用Python将CSV文件插入PostgreSQL时触发TypeError的解决方法
解决psycopg2插入CSV数据时的TypeError及高效导入方法
先修正你当前代码的问题
触发TypeError有两个核心原因,对应修改如下:
- 占位符错误:psycopg2使用
%s作为参数占位符,而非? - 参数传递错误:
cur.execute()的第二个参数必须是元组/列表这类可迭代对象,不能拆分传递多个独立参数
修正后的代码:
for row in departments.itertuples(): cur.execute(''' INSERT INTO departments VALUES (%s, %s, %s) ''', (row.id, row.department_name, row.annual_budget)) # 用元组包裹所有参数 conn.commit()
更高效的CSV导入方法(推荐)
逐行循环插入效率极低,尤其是数据量较大时,推荐以下两种批量导入方式:
方法一:用pandas的to_sql直接写入
代码简洁且适配性强,适合大多数场景:
from sqlalchemy import create_engine # 创建数据库连接引擎 engine = create_engine('postgresql://postgres:123@localhost:5432/postgres') # 将DataFrame写入数据库表 departments.to_sql('departments', engine, if_exists='append', index=False)
if_exists='append':表已存在则追加数据,可选replace(替换表)或fail(表存在则报错)index=False:不把DataFrame的索引列写入数据库
方法二:用psycopg2的copy_from(性能最优)
模拟PostgreSQL原生COPY命令,是超大文件批量导入的最优选择:
import io # 将DataFrame转为内存中的CSV格式对象 output = io.StringIO() departments.to_csv(output, sep='\t', header=False, index=False) output.seek(0) # 将文件指针移至开头 # 执行批量导入 cur.copy_from(output, 'departments', null='', sep='\t') conn.commit()
内容的提问来源于stack exchange,提问作者amatof
相关产品推荐
相关产品推荐

