我正在编写一个函数,它接受一些参数并构建一个 SQL 查询字符串。我目前已按名称将每个关键字参数分配给字符串,并且我认为必须有一种更简单的方法来自动格式化字符串中所需的关键字参数。我想知道如果参数名称匹配,是否可以自动格式化(或分配)关键字参数给查询字符串。
这是我当前的功能:
def create_query(
who_id,
what_id=None,
owner_id=None,
subject,
description,
due_date,
is_closed=False,
is_priority=False,
is_reminder=True,
):
query_str = """
'WhoId':'{who_id}',
'Subject':'{subject}',
'Description':'{description}',
'ActivityDate':'{due_date}',
'IsClosed':'{is_closed}',
'IsPriority':'{is_priority}',
'IsReminderSet':'{is_reminder}',
""".format(
who_id=who_id,
subject=subject, # Mapping each of these to the
description=description, # identically named variable
due_date=due_date, # seems dumb
is_closed=is_closed,
is_priority=is_priority,
is_reminder=is_reminder,
)
我想要更像这样的东西:
def create_query(**kwargs):
query_string = """
'WhoId':'{who_id}',
'Subject':'{subject}',
'Description':'{description}',
...
""".format(
for key in **kwargs:
if key == << one of the {keyword} variables in query_string >>:
key = << the matching variable in query_string >>
最佳答案
def create_query(**kwargs):
query_string = """
'WhoId':'{who_id}',
'Subject':'{subject}',
'Description':'{description}',
...
""".format(**kwargs)
print(query_string)
可以像这样使用:
create_query(who_id=123, subject="Boss", description="he's bossy",
will_be_ignored="really?")
打印:
'WhoId':'123',
'Subject':'Boss',
'Description':'he is bossy',
...
请注意我输入的附加参数will_be_ignored
。它只会被忽略。您不必自己过滤。
但最好不要自己构建查询字符串。让数据库连接器来处理它。例如,如果我的示例说“他很专横”,那么这会破坏查询,因为它使用 '
作为分隔符。您的数据库连接器应该允许您使用占位符和值对其进行查询,然后用值正确替换占位符。
替代方案:
def create_query(**kwargs):
parameters = (('WhoId', 'who_id'),
('Subject','subject'),
('Description', 'description'))
query_string = ','.join(r"'{}':'{{{}}}'".format(name, kwargs[id])
for name, id in parameters
if id in kwargs)
print(query_string)
create_query(who_id=123, description="he's bossy",
will_be_ignored="really?")
打印:
'WhoId':'{123}','Description':'{he's bossy}'
关于python - 自动将参数格式化为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30143276/