我生成用于更新现有数据库中的记录的SQL语句。我使用pymssql作为我的db api。有没有办法让这个代码更pythonic?
def update_statement(table, keys:list, data:dict):
"""
This function takes a table name, the keys for the table, and a dictiary for the record to be updated into the table.
A string representing the SQL statement to be used in the session is returned.
:param table: The name of the table to be updated.
:param keys: The primary key/ keys for the table.
:param data: A dictionary representing the data that is to be updated against.
:return: The return value is a string representing the SQL statement to be used in the session.
"""
h = 'UPDATE {} SET'.format(table)
# Generate SET Clauase
for key, value in data.items():
if key in keys:
continue
else:
c = '{} = {},'.format(key, value)
h = ' '.join([h, c])
h = h.strip(',')
h = ' '.join([h, 'WHERE'])
# Generate WHERE clause
for key in keys:
h = ' '.join([h, '{} = {}'.format(key, data[key])])
h = ''.join([h, ','])
h = h.strip(',')
# Add closing semicolon.
h = ''.join([h, ';'])
# Return sql statement
return h
我想要从字符串模块实现Template类,但是无法找到一种方法能够将可迭代数量的变量传递给模板并在每次迭代结束时添加逗号(最后一次迭代除外)。
答案 0 :(得分:2)
首先,自己做这个SQL语句是坏主意。您最好永远不会将值传递给SQL,您可以使用SQLAlchemy 等工具自动构建语句。
那就是说你可以做更多的pythonic方式是以下三个语句(替换整个函数):
h1 = ', '.join('{} = {}'.format(k,v) for k,v in data.items() if k not in keys)
h2 = ', '.join('{} = {}'.format(k,data[k]) for k in keys if k in data)
return 'UPDATE {} SET {} WHERE {}'.format(table,h1,h2)