Python-Redshift SQL查询中的动态变量 [英] Python - Dynamic variable in Redshift SQL Query
问题描述
我正在python环境中进行开发,我想使用psycopg2
I'm developing in a python environment and I want to call an sql query using psycopg2
让我们说我在.sql文件中具有以下UNLOAD命令:
Lets say I have the following UNLOAD command in an .sql file:
UNLOAD
(
'
Some SQL Query
'
)
TO 's3://%PATH%'
...
在sql文件中,%PATH%
应该是明确的,例如:'folder1/folder3/file_name'
.
In the sql file the %PATH%
should be explicit like: 'folder1/folder3/file_name'
.
但是我希望python程序在运行时设置此%PATH%
.这意味着.sql文件包含类似%PATH%
之类的内容,并且仅在运行时设置.
But I want the python program to set this %PATH%
in runtime. which means that the .sql file containts something like %PATH%
and will be set only in runtime.
有什么想法吗?
推荐答案
您只需指定替换字段,并使用format命令.
You simply specify a replacement field in your SQL file, and the use a format command.
像这样创建文件
UNLOAD ('Some SQL Query')
TO 's3://{bucket}/{key}'
并像
template = open('file1.sql', 'r').read()
query = template.format(bucket='mybucket', key='folder/file.csv')
这篇关于Python-Redshift SQL查询中的动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!