繁体   English   中英

如果主键存在则插入或更新到 postgreSQL 表 with.to_sql()

[英]Insert or update if primary key exists into postgreSQL table with .to_sql()

我有一个 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.

现在,我想做的是:

  • 使用已存在的键(日期)更新行
  • 如果键(日期)不存在,则插入一个新行

我检查了以下文档: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html但我无法使用 DataFrame.to_sql() function 找到任何选项.

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

有什么方法可以使用.to_sql() function 更新/插入行吗?

您可以将my_table dataframe(其中包含您要发送到数据库中的的新值)转换为numpy 记录数组,并将其添加到在您的评论中执行function 时使用的查询 ^:

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;")

(这对我有用,希望对您有所帮助!)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM