I am using sqlalchemy write to Postgres.
import sqlalchemy
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres@localhost:5432/mydb')
I want to append a pandas dataframe, df
, to table
in mydb
.
Both have the same column names, key
and value
.
key
is the primary key in table
.
Some key values in df
are already in table
.
(1) Append fails:
df.to_sql('table',engine,if_exists='append')
This fails (IntegrityError
) because some keys in df
are already in table
.
(2) I convert df
to a record array and try writing to table
:
conn = engine.connect()
query=''' insert or replace into table (key,value) values (?,?) '''
conn.executemany(query,df.to_records())
This works with sqlite (Appending Pandas dataframe to sqlite table by primary key).
But, it fails here (ProgrammingError: syntax error at or near "or"
).
What's the right way to do this using postgres and sqlalchemy?