【问题标题】:Dealing with null in update where clause without hard-coding a statement在不对语句进行硬编码的情况下处理 update where 子句中的 null
【发布时间】:2017-09-08 15:35:06
【问题描述】:

我想编写一个生成update 语句的方法,而无需对列和值进行硬编码。该语句将包含可选的where 子句并将传递给executemany,该子句仅包含列和值,其中没有select。示例:

update TABLE
set
    Col1 = 'a',
    Col2 = 'b',
    Col3 = 'c'
where
    Col4 = 'd'
        and Col5 = 'e'
        and Col1 is null;

到目前为止我写的:

def update(self, table_name, update_columns, values, where_columns=None, where=True):
    update_columns_and_values = self.generator.generateColumnsAndPlaceholders(update_columns)
    if where:
        where_clause = self.generator.generateWhereClause(where_columns)
    else:
        where_clause = ''
    query = '''
            update {t}
            set
                {cv}
            {w}
        '''.format(t=table_name, cv=update_columns_and_values, w=where_clause)
    self.cursor.executemany(query, values)
    self.connection.commit()

def generateColumnsAndPlaceholders(columns):
    if type(columns) is str:
        columns = columns.split(', ')
    return ', \n'.join([str(c) + ' = ' + "'%s'" for c in columns])

现在,我应该如何编写一个函数 generateWhereClause,它接受任意数量的列并返回一个 where 子句,其中占位符针对非空值(用 = 表示)和空值(用is null)? 另外,我认为generateColumnsAndPlaceholders 返回的字符串由于占位符周围的单引号而没有为null 准备。如果是这样,我应该如何改变它?

一般来说,如果没有硬编码特定语句,我如何处理更新语句中的null

【问题讨论】:

    标签: python mysql python-2.7 null sql-update


    【解决方案1】:

    生成查询的函数 - 它采用表名、列 {column: value} 的值字典和约束字典,将 None 作为约束 {column: constraint}

    def update_query(table_name, values, constraints):
        v_list = [k + '=' + '"' + v + '"' for k, v in values.iteritems()]
        v_query = ', '.join(v_list)
        c_list = [k + (' IS NULL' if c is None else '=' + '"' + c + '"') for k, c in constraints.iteritems()]
        c_query = ' AND '.join(c_list)
        return 'UPDATE ' + table_name + ' SET ' + v_query + ' WHERE ' + c_query
    

    测试代码:

    tn = "table"
    vl = {"Col1":"a","Col2":"b","Col3":"c"}
    cn = {"Col4":"d","Col5":"e","Col":None}
    

    结果:

    UPDATE table SET Col2="b", Col3="c", Col1="a" WHERE Col6 IS NULL AND Col4="d" AND Col5="e"
    

    我希望订单对您来说不是问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      相关资源
      最近更新 更多