【问题标题】:Format string in python using sql.Literal使用 sql.Literal 在 python 中格式化字符串
【发布时间】: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']))

【问题讨论】:

    标签: python sql json


    【解决方案1】:

    这样做最易读的方法可能是保持您的代码不变,但在其前面加上以下内容:

    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'
    

    这样config_study 中的缺失值就用默认值填充。

    【讨论】:

    • 我的python脚本是这样开始的,只是为了让你知道我15天前开始学习python,所以我不知道。我现在将我的脚本设置为这样开始,但它失败了,你知道为什么吗?
    • 这是不可读的。请编辑您的原始帖子以包含脚本的相关部分。
    • def 下面的行应该缩进 - 它在函数内部...
    • 实际上,在脚本中是这样,但是我将您的 if 代码设置为错误,没有缩进,已修复,我现在正在测试它:),谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2012-07-25
    • 1970-01-01
    • 2019-11-28
    • 2011-07-28
    相关资源
    最近更新 更多