简体   繁体   中英

Format string in python using sql.Literal

I am executing this SQL query in a python script, in the config_study dictionary (got from json file), I have provided objects, like start_date, study_name etc. I want to enable that start_date or end_date are optional, so if not provided I want to use default values like '1900-01-01', '1900-01-01'. If they are provided I would like to use them as it is now.

How to set a default value in this query for 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']))

Probably most readable way of doing this is to leave your code untouched, but precede it with the following:

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'

so that missing values in config_study are filled with defaults.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM