使用.to_sql()在postgreSQL表中插入或更新主键



我有一个包含多个列的pandas DataFrame,我想使用.to_sql():

将其存储到postgreSQL数据库中。
my_table.to_sql('table', con=engine, schema='wrhouse', if_exists='append', index=False)

我设置了一个主键(日期),以避免重复条目。所以当我的主键在数据库中不存在时,上述命令可以工作。

但是,如果这个键存在,我得到以下错误:

IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "table_pkey"
DETAIL:  Key (date)=(2022-07-01 00:00:00) already exists.

现在,我要做的是:

  • 用已经存在的Key(date)更新行
  • 在Key(date)不存在的情况下插入新行

我检查了文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html,但我无法通过使用DataFrame.to_sql()函数找到任何选项。

另外,如果我将if_exists='append'参数更改为if_exists='replace',它将删除整个表,这不是我想要的。

是否有任何方法来更新/插入行使用。to_sql()函数?

您可以将my_table数据框(它包含您想要发送到数据库中的的新值)转换为numpy记录数组,并将其添加到注释^:

execute

函数中使用的查询中。values = str(list(my_table.to_records(index=False)))[1:-1]

conn.execute(f"INSERT INTO wrschema.table (date, first_hour, last_hour, quantity) VALUES {values} ON CONFLICT (date) DO UPDATE SET first_hour = EXCLUDED.first_hour, last_hour = EXCLUDED.last_hour, quantity = EXCLUDED.quantity;")

(这是我的工作,希望它帮助!)

最新更新