python - 使用 Psycopg2 从 Redshift 写入文件抛出异常

标签 python python-2.7 amazon-redshift psycopg2 psycopg

我正在使用 Python 2.6,我想从 Redshift 的名为“user_data”的表中读取数据并使用 psycopg2 写入文件。我在“光标”中获取记录,并以这种方式尝试写入文件:

fout = open('user_data', 'w')
cursor.copy_to(fout,"user_data", sep='|')

当我执行此操作时,它会抛出以下错误:

psycopg2.ProgrammingError: syntax error at or near "stdout"
LINE 1: COPY user_data TO stdout WITH DELIMITER AS

它想告诉我什么?这个问题的解决办法是什么??

最佳答案

不幸的是,Amazon Redshift 不支持复制到 STDOUT。您可以通过两种方式完成您的任务。第一个是按照 @kadalamittai 建议进行操作(迭代游标并在 python 中写入文件),第二个是使用 UNLOAD 命令。在处理大量数据时,我会推荐后者。

UNLOAD 使您能够将查询结果以 CSV 文件格式直接输出到 Amazon S3。示例:

UNLOAD ('select * from users where last_seen_dt>\'2016-11-10\'')
TO 's3://object-path/name-prefix'

更多信息about the UNLOAD command here .

然后您可以使用 boto从 S3 下载文件:

import boto3
s3 = boto3.resource('s3')
s3_client = boto3.client('s3')

s3_client.download_file('QueryResultsBucket', 'remote_query_results.csv', 'query_results.csv')
print(open('query_results.csv').read())

关于python - 使用 Psycopg2 从 Redshift 写入文件抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40677218/

相关文章:

python - 如何检索两个 3D 向量之间的角度?

Python 2.7,操作系统检测返回值

Python Turtle mainloop() 用法

python - 如何将行和列的特征成对组合成keras中的特征矩阵?

php - 如何在我的 PHP-Apache-PostgreSQL 站点中嵌入 python 脚本?

json - 您可以在 Redshift 上存储 JSON 字段吗?

jdbc - 找不到适用于 jdbc :redshift: 的合适驱动程序

amazon-web-services - 从 S3 加载 Redshift(带分区)

python - 当用户调用 Ctrl-C 时保存程序状态

python - 计算两行之间的时间差