首页 > 解决方案 > 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 万行,请指教。

标签: pythonpython-3.xamazon-web-servicesamazon-redshift

解决方案


我同意@mdem7 在评论中的建议,使用插入 1-5 百万数据dataframe根本不是一个好主意,您将面临性能问题。

最好使用S3加载Redshift方法。这是您的代码来执行TruncateCopy命令。

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


推荐阅读