我正在编写一个函数,它接受一些参数并构建一个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 >>
可以这样使用:
印刷品:
注意我输入的附加参数
will_be_ignored
。它将被忽略。你不必自己过滤。你知道吗但最好不要自己构建查询字符串。让数据库连接器来处理。例如,如果我的示例说“他很专横”,那么这将破坏查询,因为它使用
'
作为分隔符。数据库连接器应允许您使用占位符和值为其提供查询,然后使用值正确替换占位符。你知道吗备选方案:
印刷品:
相关问题 更多 >
编程相关推荐