【发布时间】: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