Muk*_*thu 8 python amazon-s3 amazon-web-services amazon-redshift-spectrum
conn_string = "dbname='{}' port='{}' user='{}' password='{}' host='{}'"\
.format(dbname,port,user,password,host_url)
sql="""UNLOAD ('select col1,col2 from %s.visitation_hourly_summary_us where col4= '2018-07-10' and col5= '1';') TO 's3://%s/%s/%s.csv' \
credentials 'aws_access_key_id=%s;aws_secret_access_key=%s' \
MANIFEST GZIP ALLOWOVERWRITE;Commit;""" \
% (schema_name,s3_bucket_name, schema,table,aws_access_key_id,\
aws_secret_access_key)
con = psycopg2.connect(conn_string)
cur = con.cursor()
cur.execute(sql)
Run Code Online (Sandbox Code Playgroud)
我正在尝试执行上面的脚本来读取表,然后在 S3 中创建一个文件
由于我的列是字符串,因此我无法跳过单引号,并且由于语法错误而出现错误
另外,我试过在 where 条件下给出 \ 仍然显示相同的错误。
任何帮助将不胜感激。
谢谢
Fac*_*act 14
您还可以使用 postgres 样式:
unload
($$
select * from table where id='ABC'
$$)
to 's3://bucket/queries_results/20150324/table_dump/'
credentials 'aws_access_key_id=;aws_secret_access_key='
;
Run Code Online (Sandbox Code Playgroud)
您可能希望使用两个单引号将值括起来。
如果您的查询包含引号(例如将文字值括起来),请将文字放在两组单引号之间——您还必须将查询括在单引号之间:
例子:
UNLOAD ('select * from venue where venuestate=''NV''')
Run Code Online (Sandbox Code Playgroud)
取自红移文档:https : //docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html
小智 4
正如 Sarang 所说,只需将查询的 col4 和 col5 值中的单引号替换为双引号即可。
不过,我建议您将字符串分解成更小的块,更易于阅读和维护。这样,您应该能够execute按照 chepner 的建议(和MySQL 文档)使用:
# Create the inner SQL statement. Notice the single quotes for the general
# string and the double quotes for the col4 and col5 values
sql_stmt = ('SELECT col1, col2 '
'FROM %s.visitation_hourly_summary_us '
'WHERE col4 = "2018-07-10" AND col5= "1";' % schema_name)
# Format the s3 path
s3_target = 's3://%s/%s/%s.csv' % (s3_bucket_name, schema, table)
# Format credentials string
s3_credentials = 'aws_access_key_id=%s;aws_secret_access_key=%s' % (
aws_access_key_id, aws_secret_access_key)
# Create a tuple with all preformatted strings
data = (sql_stmt, s3_target, s3_credentials)
# Format the s3 query skeleton
s3_stmt = ("UNLOAD ('%s') TO '%s' "
"CREDENTIALS '%s' "
"MANIFEST GZIP ALLOWOVERWRITE;Commit;")
con = psycopg2.connect(conn_string)
cur = con.cursor()
cur.execute(s3_stmt, data)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4514 次 |
| 最近记录: |