有什么方法可以让这个python字符串语句更pythonic?



我正在生成用于更新现有数据库中的记录的 SQL 语句。我正在使用pymssql作为我的数据库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 类,但找不到一种方法能够将可迭代数量的变量传递给模板并在每次迭代的末尾添加一个逗号(最后一次迭代除外(。

首先,自己生成此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)

最新更新