将DataFrame数据插入PostgreSQL现有表时遇DatabaseError报错求助
问题解决:Pandas向PostgreSQL插入DataFrame报错
问题重现
执行以下代码向PostgreSQL现有表插入DataFrame时出现数据库语法错误:
sql_engine = create_engine('postgresql://user:pw@host:port/db_name', echo=False) connection = sql_engine.raw_connection() combined_df.to_sql('clients', connection, schema = 'direct' index=False, if_exists='append')
报错信息:
DatabaseError: Execution failed on sql '
SELECT
name
FROM
sqlite_master
WHERE
type IN ('table', 'view')
AND name=?;
': syntax error at or near ";"
LINE 8: AND name=?;
^
错误原因
- 连接对象类型错误:
to_sql需要传入SQLAlchemy的Engine或Connection对象,而raw_connection()返回的是数据库原生连接,pandas会默认将其识别为SQLite连接,因此执行了SQLite专属的sqlite_master查询语句,导致PostgreSQL无法识别。 - 代码语法错误:
schema = 'direct'后面缺少逗号,导致index=False参数解析错误。
修正后的代码
sql_engine = create_engine('postgresql://user:pw@host:port/db_name', echo=False) # 直接使用SQLAlchemy Engine对象,无需raw_connection combined_df.to_sql( 'clients', sql_engine, schema='direct', index=False, if_exists='append' )
或者使用SQLAlchemy的Connection对象:
sql_engine = create_engine('postgresql://user:pw@host:port/db_name', echo=False) with sql_engine.connect() as connection: combined_df.to_sql( 'clients', connection, schema='direct', index=False, if_exists='append' )
关键说明
- 避免使用
raw_connection(),因为它返回的是数据库原生连接,pandas无法正确识别对应的数据库方言。 - 确保函数参数的语法正确,参数之间用逗号分隔。
内容的提问来源于stack exchange,提问作者Denis
相关产品推荐
相关产品推荐

