在帶有參數的 python MySQL IN 子句中使用字串列表
P粉523335026
P粉523335026 2024-03-27 21:19:06
0
2
378

我嘗試在 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粉523335026
P粉523335026

全部回覆(2)
P粉809110129

您可以將 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"
P粉057869348

嘗試以下操作:

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 為空的情況下呼叫。如果沒有,您將需要處理此案。
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!