通过sqlalchemy用重复键写入Postgres表

2024-04-25 00:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用sqlalchemy写入Postgres。在

import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres@localhost:5432/mydb')

我想在mydb中的table中附加一个pandas数据帧df。在

两者都有相同的列名,key和{}。在

keytable中的主键。在

df中的一些键值已经在table中。在

(1)追加失败:

^{pr2}$

这失败(IntegrityError),因为df中的一些键已经在table中。在

(2)我将df转换为记录数组,并尝试写入table

conn = engine.connect()
query=''' insert or replace into table (key,value) values (?,?) '''
conn.executemany(query,df.to_records())

这适用于sqlite(appending-pandas-dataframe-to-sqlite-table-by-primary-key">Appending Pandas dataframe to sqlite table by primary key)。在

但是,它在这里失败了(ProgrammingError: syntax error at or near "or")。在

使用postgres和sqlalchemy的正确方法是什么?在


Tags: ortokeyimportpandasdfsqlitesqlalchemy
1条回答
网友
1楼 · 发布于 2024-04-25 00:22:44

迭代记录并捕捉异常似乎是最好的解决方案?在

inp=df.to_records(index=True)
for i in inp: 
   q=''' insert into table (key,value) values %s '''%i
   try:
     conn.execute(q)
   except IntegrityError:
     print "Key in table."

相关问题 更多 >