简体   繁体   English

使用SQLAlchemy和python数据框架替换和更新Postgresql表

[英]Replace and update Postgresql tables using SQLAlchemy and python data-frames

I have a python script which brings data from mongodb, elaborate it and write the final results into a postgresql db as a table: 我有一个python脚本,该脚本从mongodb中获取数据,对其进行详细说明并将最终结果作为表格写入到postgresql db中:

import sqlalchemy
from sqlalchemy import create_engine

engine = create_engine('postgresql://user:password@localhost/db')
df.to_sql("table", engine)

The code functions perfectly but when i rerun the code it gives an error that the table already exists. 该代码运行正常,但是当我重新运行该代码时,它给出了该表已存在的错误。

My question is what are the necessary commands to let it either overwrite the existing table or just update it with new rows? 我的问题是什么必要的命令来使其覆盖现有表或仅使用新行对其进行更新?

I found a very simple answer which do the trick in pandas docs . 我在pandas docs中找到了一个非常简单的答案,可以解决问题。

df.to_sql("table", engine, if_exists='replace')

The default setting is if table exists session fails 默认设置是表是否存在会话失败

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

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