【发布时间】:2021-08-16 10:46:41
【问题描述】:
我将执行COPY命令的以下python lambda代码设置为redshift。
bucket_name = get_bucket_name(event)
file_name = get_file_name(event)
table = bucket_name.replace('-','_')
url = f's3://{bucket_name}/{file_name}'
query = sql.SQL(''' truncate test_Schema.{};
commit;
copy test_Schema.{}
from {}
iam_role 'arn:aws:iam::123344:role/test'
timeformat as 'auto'
ACCEPTINVCHARS
CSV;''').format(*map(sql.Identifier,(table,table,url)))
print(query)
cur = con.cursor()
cur.execute(query, (url,))
con.commit()
通过使用标识符,我可以使用变量并设置 S3 存储桶目标。
但它返回了以下错误。看来双引号引起了错误..
truncate test_Schema."test";
commit;
copy jp_icqa_ddl."operation_defect_detail"
from "s3://test_Schema/test_20210816.csv"
iam_role 'arn:aws:iam::123344:role/test'
timeformat as 'auto'
ACCEPTINVCHARS
CSV;
[ERROR] SyntaxError: syntax error at or near ""s3://test_Schema/test_20210816.csv""
LINE 4: from "s3://test_Schema/test_20210816...
^
Traceback (most recent call last):
File "/var/task/s3-to-redshift.py", line 63, in lambda_handler
cur.execute(query, (url,))
有什么办法可以避免吗?
如何处理标识符中的双引号?
谢谢
【问题讨论】:
-
在
cur = con.cursor()之前执行print(query)- 您将在cloudwatch 中获得输出。分享输出。 -
在创建查询时尝试使用 f 字符串。它使代码更具可读性。见realpython.com/python-f-strings
标签: python amazon-s3 aws-lambda amazon-redshift psycopg2