我有一个 Python 函数,它接收大量变量,并从中构建一个 SQL 查询:
def myfunc(name=None, abbr=None, grade=None, ...)
这些值应该构建一个 SQL 查询。为此,None
应将等于的那些更改为NULL
,而将存储有用值的那些应包含在'
s 中:
name="'"+name+"\'" if name else 'NULL'
abbr="'"+abbr+"\'" if abbr else 'NULL'
...
Lots of lines here - that's my problem!
...
然后,
query="""INSERT INTO table(name, abbr, ...)
VALUES (%(name)s, %(abbr)s, ...) """ locals()
cur.execute(query)
是否有更好、更 Pythonic 的方式来根据此规则更改变量内容?
亚当