将变量数目的参数从Python传递到mysql
我想构建一个参数数量可变的查询:将变量数目的参数从Python传递到mysql,python,mysql,Python,Mysql,我想构建一个参数数量可变的查询: 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}) 但这会导致一个警告(默认情况下不会显示): 截断了不正确的双精度值:“30,12” 并且只使用第一个值,其余的
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})
但这会导致一个警告(默认情况下不会显示):
截断了不正确的双精度值:“30,12”
并且只使用第一个值,其余的忽略。
所以我现在正在使用这个小技巧:
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
;")
我知道这些是有效的值(来自枚举),但我甚至可以排除最遥远的SQL注入可能性。动态构造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)
注意:以上内容不适用于空id列表。用一个条件来保护它:
if not group_ids:
# skip execution of the query.
抱歉,不工作:mysql.connector.errors.ProgrammingError:处理格式参数失败;Py thon'list'无法转换为MySQLtype@MKesper,确保传递的是字符串列表
sql
,以及group\u id
。