将可变数量的参数从Python传递到mysql

MKe*_*per 3 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})
Run Code Online (Sandbox Code Playgroud)

但这会导致警告(默认情况下不会显示!):截断了不正确的 DOUBLE 值:'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
    ;")
Run Code Online (Sandbox Code Playgroud)

我知道这些是有效值(来自枚举),但我会消除 SQL 注入的最遥远的可能性。

fal*_*tru 5

动态构造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)
Run Code Online (Sandbox Code Playgroud)

注意:以上不适用于空 id 列表。用一个条件来保护它:

if not group_ids:
    # skip execution of the query.
Run Code Online (Sandbox Code Playgroud)

  • @DavidManess,您应该将参数作为列表传递:`cursor.execute(sql, group_ids + [c_value])` (2认同)