[英]Passing variable number of args from Python to mysql
I want to build a query with variable number of arguments: 我想建立一个具有可变数量参数的查询:
group_ids = ', '.join(str(Rules[s].value) for s in groups)
cursor.execute("SELECT a, b, c
FROM my_table
WHERE a IN (%(group_ids)s)
;",
{'group_ids': group_ids})
But that results in a warning (which is not shown by default!): Truncated incorrect DOUBLE value: '30, 12' and only the first value is used, the rest omitted. 但这会导致警告(默认情况下未显示!):截断了错误的DOUBLE值:'30,12',仅使用了第一个值,其余的省略了。 So I'm using this little hack right now:
所以我现在正在使用这个小技巧:
group_ids = ', '.join(str(Rules[s].value) for s in groups)
cursor.execute('\n'.join("SELECT a, b, c",
"FROM my_table",
"WHERE a IN %s" % group_ids
;")
I know these are valid values (coming from an enum) but I would get rid of even the remotest possibility of SQL injections. 我知道这些是有效的值(来自一个枚举),但是我什至摆脱了SQL注入的可能性很小。
Construct the parameter part of the SQL dynamically: 动态构造SQL的参数部分:
group_ids = [str(Rules[s].value) for s in groups]
sql = "SELECT a, b, c FROM my_table WHERE a IN (%s)" % (
','.join(['%s'] * len(group_ids))
)
cursor.execute(sql, group_ids)
NOTE: Above will not work for an empty id list. 注意:上面的内容不适用于空ID列表。 Guard it with a condition:
使用以下条件进行保护:
if not group_ids:
# skip execution of the query.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.