Python %重复使用多个变量的长查询中的字符串格式

Python %重复使用多个变量的长查询中的字符串格式,python,python-3.x,formatting,psycopg2,Python,Python 3.x,Formatting,Psycopg2,我正在读这篇文章,也在做一些搜索 我使用psycopg2将字符串作为sql查询执行: import credentials as creds import psycopg2 start_date = '2020-01-01' end_date = '2020-01-02' another_date = '2019-12-31' my_sql_query = """ with t1 as ( select * from table where date &

我正在读这篇文章,也在做一些搜索

我使用psycopg2将字符串作为sql查询执行:

import credentials as creds
import psycopg2
start_date = '2020-01-01'
end_date = '2020-01-02'
another_date = '2019-12-31'


my_sql_query = """

with 

t1 as (
select * 
from table
where date >= %s), # should be start_date

t2 as (
select *
from anothertable
where created_date >= %s # should be start_date
and created_date <= %s # should be end_date
)

t3 as (
select *
from anotheranothertable
where date >= %s # should be another_date
)

select t1.blah, t2.ha, t3.*
from t1
join t2 on t2.id = t1.id
join t3 on t3.id = t1.id

"""
这里有4%s个实例。我实际上有三个变量:

start_date
end_date
another_date
我使用的实际查询更长,并且在整个过程中多次引用这3个日期变量

是否有一种更简单的方法来传递它们,以便它们可以通过变量名或其他方法(而不是顺序)引用

根据上面的示例,如果我重复引用某个变量,我必须调用cursor.execute,按变量出现的顺序执行,包括重复:

cursor.execute(my_sql_query, (start_date, start_date, end_date, another_date))
但在我的真实剧本中,它会变得更长

cursor.execute(my_sql_query, (start_date, start_date, end_date, another_date, start_date, end_date, end_date, another_date, start_date))

“正确”的方法是什么?

您可以先自己填充变量,然后调用cursor.execute


您可以先自己填充变量,然后调用cursor.execute


您可以使用它在SQL中重复它,并让数据库API以更安全的方式处理替换:


您可以使用它在SQL中重复它,并让数据库API以更安全的方式处理替换:


您是否检查了执行的文档?有些函数可以使用带有%名称的字符串,但我不知道execute是否也可以使用它。您可以使用.format或f-strings而不是%方法,它允许变量/索引引用。是否检查了execute文档?有些函数可以使用带有%名称的字符串,但我不知道execute是否也可以使用它。您可以使用.format或f-strings代替%方法,它允许变量/索引引用。
cursor.execute(my_sql_query, (start_date, start_date, end_date, another_date, start_date, end_date, end_date, another_date, start_date))
start_date = '2020-01-01'
end_date = '2020-01-02'
another_date = '2019-12-31'

date_map = {}
date_map['start_date'] = start_date
date_map['end_date'] = end_date
date_map['another_date'] = another_date

my_sql_query = """

with 

t1 as (
select * 
from table
where date >= {start_date}), # should be start_date

t2 as (
select *
from anothertable
where created_date >= {start_date} # should be start_date
and created_date <= {end_date} # should be end_date
)

t3 as (
select *
from anotheranothertable
where date >= {another_date} # should be another_date
)

select t1.blah, t2.ha, t3.*
from t1
join t2 on t2.id = t1.id
join t3 on t3.id = t1.id

"""

my_sql_query = my_sql_query.format(**date_map)
#cursor.execute(my_sql_query)
print(my_sql_query)