如何在Python中将Python字符串变量添加到SQL字符串变量的一部分?

时间:2018-03-27 22:04:10

标签: python r sqlalchemy pycharm amazon-redshift

我在Python中使用SQLAlchemy来执行Redshift SQL查询。我正在定义我想要作为python字符串执行的SQL我想创建一些额外的python字符串变量,它们将成为SQL字符串的一部分。例如,在下面的示例中,SQL查询中的表名可以从python变量" table_string"构建。加上表名的其余部分。在此示例中,生成的表名称为" test_table_name"。

table_string = 'test_'

create_test_sql_string_python='''
begin;
create table 'table_string'+'table_name'
(id int not null, name varchar(40), date timestamp);
end;
'''
execute(sa.text(create_test_sql_string_python).execution_options(autocommit=True))

我在R中做了类似的事情,我想知道python相当于什么。这是R样本:

table_string <- 'test_'
dbSendQuery(redshift,paste0("begin;
                         create table ",table_string,"table_name
                         (id int not null, name varchar(40), date timestamp);
                          end;"))

2 个答案:

答案 0 :(得分:3)

可以使用.format方法(请参阅PyFormat Documentation)。在你的情况下,它看起来像这样:

table_string = 'test_'

create_test_sql_string_python='''
begin;
create table {0}table_name
(id int not null, name varchar(40), date timestamp);
end;
'''.format(table_string)

在字符串中放置{0}将替换.format()内的第一个参数,该参数可能有多个参数。

答案 1 :(得分:2)

我无法对SQL语句本身发表评论,但您可以使用format在此处传递变量。

字符串看起来像:

"""
begin;
create table {} (id int not null, 
                 name varchar(40), 
                 date timestamp);
end;
""".format(table_string)