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

使用Pandas向PostgreSQL写入DataFrame时遇schema参数重复值错误

解决DataFrame写入PostgreSQL时的TypeError问题

问题原因

触发的TypeError: __init__() got multiple values for argument 'schema'错误,核心原因是你将**引擎的连接实例(self.con = self.engine.connect()返回的对象)**传给了df.to_sql()的con参数。当配合schema参数使用时,这个连接实例会和显式传入的schema参数产生冲突,导致SQLAlchemy内部初始化MetaData时重复传递schema参数。

修复方案

直接将SQLAlchemy引擎对象(self.engine)传给df.to_sql()的con参数,而非使用engine.connect()返回的连接实例。调整后的代码如下:

修改后的数据库初始化代码

self.engine = create_engine("postgresql://postgres:12345@localhost/postgres")
# 无需手动创建connect实例,df.to_sql会自动处理连接逻辑

正确的df.to_sql调用方式

带schema的场景:

df.to_sql(symbol, schema='xxx', con=self.engine, if_exists='append', index=False)

不带schema的场景:

df.to_sql(symbol, con=self.engine, if_exists='append', index=False)

补充说明

如果代码中需要手动执行其他SQL操作(比如使用cursor执行自定义语句),可以保留self.con = self.engine.connect()这部分逻辑,但调用df.to_sql()时必须传入引擎对象而非连接实例,避免参数冲突。

内容的提问来源于stack exchange,提问作者sinan yılmaz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 20:35:22