Python 在不硬编码语句的情况下处理update where子句中的null
我想写一个生成Python 在不硬编码语句的情况下处理update where子句中的null,python,mysql,python-2.7,null,sql-update,Python,Mysql,Python 2.7,Null,Sql Update,我想写一个生成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,
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])
现在,我应该如何编写一个函数generateWhere子句
,该函数接受任意数量的列并返回一个where
子句,其中占位符针对非空值(用=
表示)和空值(用表示为空
)进行了调整?
另外,我认为generateColumnsandplaceholder
返回的字符串没有为null
做好准备,因为占位符周围有单引号。如果是,我应该如何更改它
一般来说,我如何处理update语句中的
null
,而不硬编码特定语句?生成查询的函数-它使用表名、列值字典{column:value}
和约束字典,这些都不作为约束{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"
我希望订单不是你的问题