我正在生成用于更新现有数据库中的记录的 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
我想从 string 模块实现 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)
关于python - 有什么方法可以让这个Python字符串语句更加Pythonic吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290331/