python - 有什么方法可以让这个Python字符串语句更加Pythonic吗?

标签 python sql string templates

我正在生成用于更新现有数据库中的记录的 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/

相关文章:

python - 将字符串中的最后一个数字逐一迭代

python - 如何知道scrapy蜘蛛当前使用的是哪个用户代理?

mysql - 如何在 GROUP BY 查询中为每个组返回特定​​列的最频繁值?

javascript - 如何通过 URL 传递撇号?

python - 使用批处理文件运行 Django 项目后 Chrome 无法打开

python - 在 pickle 中存储数据时出现 IO 错误

C#在几个月内有所不同?

MySQL - 如何在使用多个过滤器查询时保持可接受的响应时间(我应该使用 Redis 吗?)

python - 删除空格并使 python 字符串中的所有小写

c - 末尾带有垃圾字符的字符串数组