编程语言
首页 > 编程语言> > python – 在Redshift查询中转义引号

python – 在Redshift查询中转义引号

作者:互联网

我试图将我的代码重构为PEP8标准以便于阅读,但我正在努力逃避SQL查询中的引号.
我有2个查询.第一个是简单的SQL查询.第二个是Redshift UNLOAD命令.

query = '''SELECT * FROM redshift_table
           LEFT JOIN
           (SELECT DISTINCT * FROM redshift_view) v
           ON redshift_table.account_number = v.card_no
           WHERE timestamp < date_trunc('day', CURRENT_DATE)
           AND timestamp >=  (CURRENT_DATE - INTERVAL '1 days')'''

unload = '''UNLOAD ('%s') to '%s'
            credentials 'aws_access_key_id=%s;aws_secret_access_key=%s'
            delimiter as '%s'parallel off ALLOWOVERWRITE''' % (query, s3_path, access_key, aws_secret, file_delimiter)

因为sql查询嵌入在UNLOAD命令中,所以我只能通过在前面添加3个反斜杠来转义引号来使它工作:’day’变为///’day ///’.
这不太理想,我想知道是否有办法绕过它.

任何帮助是极大的赞赏.谢谢.

解决方法:

由于您只需要在unload命令中的引号之前插入反斜杠,因此使用转义函数可以正常工作.这是一个例子.

def escape_quote(value):
  return value.replace("'", "\\'")

query = '''SELECT * FROM redshift_table
           LEFT JOIN
           (SELECT DISTINCT * FROM redshift_view) v
           ON redshift_table.account_number = v.card_no
           WHERE timestamp < date_trunc('day', CURRENT_DATE)
           AND timestamp >=  (CURRENT_DATE - INTERVAL '1 days')'''

unload = '''UNLOAD ('%s') to '%s'
            credentials 'aws_access_key_id=%s;aws_secret_access_key=%s'
            delimiter as '%s'parallel off ALLOWOVERWRITE''' % (escape_quote(query), s3_path, access_key, aws_secret, file_delimiter)

标签:python,mysql,amazon-redshift
来源: https://codeday.me/bug/20190708/1403090.html