我正在使用 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/