首頁  >  問答  >  主體

在帶有參數的 python MySQL IN 子句中使用字串列表

我嘗試在 python 中使用 in-query 。但我對此有不同的例外。

第一次嘗試是:

query = """select keyword
               from keyword 
               where keyword in %(ids)s and country = %(country)s"""
cursor.execute(query, {'ids': tuple(ids), 'country': country})

它給出以下錯誤:Failedprocessing pyformat-parameters; Python「tuple」無法轉換為 MySQL 類型

第二次嘗試是:

str_keywords = ",".join(tuple("'" + str(i) + "'" for i in ids))

query = """select keyword
           from keyword 
           where keyword in (%s) and country = %s"""
cursor.execute(query, (str_keywords, country))

這不會給出錯誤,但不起作用。

有什麼建議嗎?

P粉523335026P粉523335026205 天前381

全部回覆(2)我來回復

  • P粉809110129

    P粉8091101292024-03-28 20:14:43

    您可以將 f 字串與元組一起使用:

    ids = ('1,2,3','54','67')
    code = 'BR'
    query = f"""select keyword
               from keyword 
               where keyword in {ids} and country_code = {code}
               and brand_app is not null"""
    query

    輸出:

    "select keyword\n           from keyword \n           where keyword in ('1,2,3', '54', '67') and country_code = BR\n           and brand_app is not null"

    回覆
    0
  • P粉057869348

    P粉0578693482024-03-28 13:21:14

    嘗試以下操作:

    params = ",".join(["%s"] * len(ids))
    query = f"""select keyword
                   from keyword 
                   where keyword in ({params}) and country = %s"""
    cursor.execute(query, (*ids, country))
    

    此處的目標是為ids 中的每個值建立一個in (%s, %s, %s, ..., %s) 子句,其中包含一個%s 佔位符。

    有幾點要注意:

    • IN 子句中的佔位符數量可能有上限。有關詳細信息,請參閱 MySQL IN 條件限制
    • 如果 ids 為空,則此查詢無效。您可能已經有一些邏輯來處理空 ids 清單的情況,或者您的程式碼可能永遠不會在 ids 為空的情況下呼叫。如果沒有,您將需要處理此案。

    回覆
    0
  • 取消回覆