我正在使用sqlalchemy写入Postgres。在
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres@localhost:5432/mydb')
我想在mydb
中的table
中附加一个pandas数据帧df
。在
两者都有相同的列名,key
和{
key
是table
中的主键。在
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的正确方法是什么?在
迭代记录并捕捉异常似乎是最好的解决方案?在
相关问题 更多 >
编程相关推荐