【发布时间】:2020-02-19 20:17:29
【问题描述】:
我正在 python 脚本中执行此 SQL 查询,在 config_study 字典(从 json 文件中获取)中,我提供了对象,如 start_date、study_name 等。我想启用 start_date 或 end_date 是可选的,所以如果不是前提是我想使用默认值,例如“1900-01-01”、“1900-01-01”。如果提供它们,我想像现在一样使用它们。
如何在此查询中为 start_date=sql.Literal(config_study['start_date']) 设置默认值?
import psycopg2
from psycopg2 import sql
def execute(conf, cur):
config_study = conf['config_study']
if 'start_date' not in config_study:
config_study['start_date'] = '1900-01-01'
if 'end_date' not in config_study:
config_study['end_date'] = '1900-01-01'
pre_query = sql.SQL("""
INSERT INTO {{tmp_output_schema_name}}."config_set"
("study_id",
"study_name",
"study_type",
"date_start",
"date_end",
"sales",
"client")
VALUES
({{study_id}},
{study_name},
{{study_type_shortname}},
{start_date},
{end_date},
'edwin@gmail.co',
'Persona client'); """).format(
study_name=sql.Literal(config_study['study_name']),
start_date=sql.Literal(config_study['start_date']),
end_date=sql.Literal(config_study['end_date']))
【问题讨论】: