[英]How to escape single quotes in Unload
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)
我正在嘗試執行上述腳本以讀取表,然后在S3中創建文件
由於我的列是字符串,所以我無法跳過單引號,並且在語法錯誤的附近獲取錯誤
另外,我嘗試在條件仍然顯示相同錯誤的地方給\\。
任何幫助將不勝感激。
謝謝
正如Sarang所說,只需在查詢的col4和col5值中用雙引號替換單引號即可解決問題。
但是,我建議您將字符串分解為較小的塊,以便於閱讀和維護。 這樣,您應該能夠按照chepner的建議(和MySQL文檔 )使用execute
:
# 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)
'(單引號可以作為發送)-> \\\\\\\\'
我在R和python中都用過這個,請找到解決方案
如果您的SQL查詢是
從sample_table中選擇*,其中register_date ='2018-12-31'
然后對於卸載命令這樣寫
sql= """unload ('Select * from tnltemp.otpsuccess_details where register_date=\\\\'2018-12-31\\\\' ')
to 's3://my-bucket/migration/exported_sample_table_' credentials
'aws_access_key_id=12234123;aws_secret_access_key=12345'
DELIMITER AS ','
NULL AS ''
parallel off;""""
cur = con.cursor()
cur.execute(sql)
您也可以使用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='
;
您可以將值放在雙引號中。 '從%s.visitation_hourly_summary_us中選擇col1,col2,其中col4 =“ 2018-07-10”和col5 =“ 1”;'
您可能希望使用兩個單引號將值引起來。
如果您的查詢包含引號(例如,將文字值括起來),則將文字放在兩組單引號之間—您還必須將查詢括在單引號之間:
例:
UNLOAD ('select * from venue where venuestate=''NV''')
取自redshift文檔: https : //docs.aws.amazon.com/redshift/latest/dg/r_UNLOAD.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.