python - Python 使用 psycopg2 将 DateFrame 写入 AWS redshift
问题描述
我想每天更新 AWS 中的一个表,我打算首先使用 Python psycopg2 删除 AWS 中公共表中的数据/行,然后将 python 数据帧数据插入该表中。
import psycopg2
import pandas as pd
con=psycopg2.connect(dbname= My_Credential.....)
cur = con.cursor()
sql = """
DELETE FROM tableA
"""
cur.execute(sql)
con.commit()
上面的代码可以删除,但我不知道如何编写python代码将My_Dataframe插入tableA。TableA 大小约为 100 万行到 500 万行,请指教。
解决方案
我同意@mdem7 在评论中的建议,使用插入 1-5 百万数据dataframe
根本不是一个好主意,您将面临性能问题。
最好使用S3
加载Redshift
方法。这是您的代码来执行Truncate
和Copy
命令。
import psycopg2
def redshift():
conn = psycopg2.connect(dbname='database_name', host='888888888888****.u.****.redshift.amazonaws.com', port='5439', user='username', password='********')
cur = conn.cursor();
cur.execute("truncate table example;")
//Begin your transaction
cur.execute("begin;")
cur.execute("copy example from 's3://examble-bucket/example.csv' credentials 'aws_access_key_id=ID;aws_secret_access_key=KEY/KEY/pL/KEY' csv;")
////Commit your transaction
cur.execute("commit;")
print("Copy executed fine!")
redshift();
在option中还有更多方法可以Copy
加快速度,从而可以并行加载数据。希望这能给你一些移动的想法。Menifest
Redshift
推荐阅读
- javascript - 将多个 refs 传递给子组件
- javascript - React Hooks 过滤列表
- c++ - 基类构造函数参数值
- c++ - 二进制“<<”:未找到采用“temperature_stats”类型右侧操作数的运算符(或没有可接受的转换),第 36 行
- android - 【Android Studio】构建项目时显示Cause: unable to find valid authentication path to requested target
- laravel - WHERE 内部 DB::raw 语句返回 0
- python - 计算 Python 中元素的出现次数
- regex - 提取电话号码
- typescript - 无法使 tsconfig 路径正常工作 (TS2307)
- typescript - Docker 中的打字稿:Visual Studio 代码主机打字稿编译器中的“找不到模块”