Python:自动更改变量内容
我有一个 Python 函数,它接收大量变量,并根据它们构建 SQL 查询:
def myfunc(name=None, abbr=None, grade=None, ...)
这些值应该构建 SQL 查询。 ,那些等于 None
的值应该更改为 NULL
,而那些存储有用值的值应该用 '
括起来:
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的方式来根据这个规则改变变量内容?
亚当
I have a Python function which receives numerous variables, and builds an SQL query out of them:
def myfunc(name=None, abbr=None, grade=None, ...)
These values should build an SQL query. For that purpose, Those who equal None
should be changed to NULL
, and those who store useful values should be embraced with '
s:
name="'"+name+"\'" if name else 'NULL'
abbr="'"+abbr+"\'" if abbr else 'NULL'
...
Lots of lines here - that's my problem!
...
And than,
query="""INSERT INTO table(name, abbr, ...)
VALUES (%(name)s, %(abbr)s, ...) """ locals()
cur.execute(query)
Is there a nicer, more Pythonic way to change the variable contents according to this rule?
Adam
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
形成 SQL 查询的最佳方法不是通过字符串格式化 -
cursor
对象的execute
方法采用带有占位符的查询字符串和一个序列(或字典,取决于您对 DB API 的具体实现)以及要替换的值;然后它将执行您需要的 None-to-Null 和字符串引用。我强烈建议您研究一下这种可能性。但是,如果您需要出于其他目的进行字符串处理,您可以执行以下操作:
然后使用字典
processed
而不是locals()
进行进一步的字符串格式化。The best way to form a SQL query is not by string-formatting -- the
execute
method of acursor
object takes a query string with placeholders and a sequence (or dict, depending on the exact implementation you have of the DB API) with the values to substitute there; it will then perform the None-to-Null and string-quoting that you require.I strongly recommend you look into that possibility. If you need string processing for some other purpose, however, you could do something like:
and then use dictionary
processed
instead oflocals()
for further string-formatting.您可以如下定义
myfunc
:其中 kwargs 是一个字典,包含传递给函数的所有命名参数。
要获取查询参数的值,您可以使用
kwargs.get(name_of_parameter, 'NULL')
。要构建查询,您只需迭代所有字典项即可。但请注意,如果您这样做,作为命名参数传递给函数的任何参数都将最终出现在查询中。You could define
myfunc
as follows:Where kwargs is a dictionary holding all named parameters passed to the function.
To get the value of a query parameter, you would use
kwargs.get(name_of_parameter, 'NULL')
. To build the query, you would just iterate over all dictionary items. Note however, that any parameter passed as a named parameter to the function will end up in the query if you do it this way.将参数传递给 psycopg2 的正确方法是使用占位符和 让驱动程序处理这些值。 None 会自动转换为 NULL,并执行正确的字符串转义。
连接字符串是一个坏主意。
The correct way to pass arguments to psycopg2 is to use placeholders and let the driver handle the values. None are converted to NULL automatically and the correct string escaping is performed.
Concatenating string is a bad idea.