【问题标题】:Redshift COPY csv in S3 using python使用 python 在 S3 中进行 Redshift COPY csv
【发布时间】:2018-12-10 07:53:43
【问题描述】:

您好,我有以下功能来保存 csv 文件:

mysql_cur = mysql_conn.cursor()
mysql_cur.execute('select * from %s where Date > "2018-01-01";' % mysql_table_name  )
description = mysql_cur.description
rows = mysql_cur.fetchall()
for row in rows:
    c.writerow(row)

然后我手动将文件上传到 S3 存储桶。

我最后一次运行 COPY 查询:

redshift_cur = redshift_conn.cursor()

sql = """copy kpi_kpireport from 's3://clab-migration/kpi.csv' 
credentials 'aws_access_key_id=ID;aws_secret_access_key=KEY/KEY/pL/KEY'
csv;"""
print(redshift_cur.execute(sql))

当我在 SQL Workbench/J 中使用 COPY 命令时它可以工作,我只是不确定我在这里做错了什么,因为执行语句中的语法不复制任何行。

【问题讨论】:

  • 您的问题是什么?现在有什么工作吗?您收到错误消息吗? redshift_conn 是否适用于其他事物,例如 SELECT 42
  • 从 Python 代码运行 COPY 命令时遇到什么错误?

标签: python copy amazon-redshift


【解决方案1】:

实际上,您没有在 Redshift 中看到数据的原因似乎是您没有启用 Auto-Commit,因此,您的命令已成功执行,但它会将 copy 数据放入 Redshift,但没有提交。因此,当您通过从 console 或您的 WorkBench/J 查询 select 时,您看不到数据。

您应该明确地开始并提交事务。 我只是给你一个简单的工作示例。

import psycopg2


def redshift():

    conn = psycopg2.connect(dbname='**_dev_**', host='888888888888****.u.****.redshift.amazonaws.com', port='5439', user='******', password='********')
    cur = conn.cursor();

    # Begin your transaction
    cur.execute("begin;")

    cur.execute("copy kpi_kpireport from 's3://clab-migration/kpi.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();

现在,如果您运行上面的代码,您将看到复制的数据。

如果你从上面的代码中删除两行,cur.execute("begin;")cur.execute("commit;") 运行它,即使运行成功没有错误,你也不会在 Redshift 中看到数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多