gpt4 book ai didi

python - 如何通过 Python Boto3 将数据加载到 Amazon Redshift?

转载 作者:太空狗 更新时间:2023-10-29 18:15:59 25 4
gpt4 key购买 nike

在 Amazon Redshift 的 Getting Started Guide 中,数据从 Amazon S3 中提取并使用 SQLWorkbench/J 加载到 Amazon Redshift 集群中。我想模拟使用 Boto3 连接到集群并将样本数据加载到集群的相同过程。 .

然而在Boto3's documentation对于 Redshift,我找不到一种方法可以将数据上传到 Amazon Redshift 集群。

我已经能够使用 Boto3 通过以下代码连接到 Redshift:

client = boto3.client('redshift')

但我不确定哪种方法可以让我创建表或将数据上传到 Amazon Redshift,就像在 tutorial with SQLWorkbenchJ 中所做的那样。 .

最佳答案

对了,你需要 psycopg2 Python 模块来执行 COPY 命令。

我的代码是这样的:

import psycopg2
#Amazon Redshift connect string
conn_string = "dbname='***' port='5439' user='***' password='***' host='mycluster.***.redshift.amazonaws.com'"
#connect to Redshift (database should be open to the world)
con = psycopg2.connect(conn_string);
sql="""COPY %s FROM '%s' credentials
'aws_access_key_id=%s; aws_secret_access_key=%s'
delimiter '%s' FORMAT CSV %s %s; commit;""" %
(to_table, fn, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY,delim,quote,gzip)

#Here
# fn - s3://path_to__input_file.gz
# gzip = 'gzip'

cur = con.cursor()
cur.execute(sql)
con.close()

我用boto3/psycopg2写了CSV_Loader_For_Redshift

关于python - 如何通过 Python Boto3 将数据加载到 Amazon Redshift?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34983043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com