簡體   English   中英

從Python傳遞可變數量的args到mysql

[英]Passing variable number of args from Python to 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})

但這會導致警告(默認情況下未顯示!):截斷了錯誤的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
    ;")

我知道這些是有效的值(來自一個枚舉),但是我什至擺脫了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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM