Ich versuche, In-Query in Python zu verwenden. Aber ich habe hiervon verschiedene Ausnahmen.
Der erste Versuch war:
query = """select keyword from keyword where keyword in %(ids)s and country = %(country)s""" cursor.execute(query, {'ids': tuple(ids), 'country': country})
Es wird folgender Fehler angezeigt: Failedprocessing pyformat-parameters; Python“tuple”無法轉(zhuǎn)換為 MySQL 類型
Der zweite Versuch war:
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))
Dies gibt keinen Fehler aus, funktioniert aber nicht.
Irgendwelche Vorschl?ge?
您可以將 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"
嘗試以下操作:
params = ",".join(["%s"] * len(ids)) query = f"""select keyword from keyword where keyword in ({params}) and country = %s""" cursor.execute(query, (*ids, country))
此處的目標(biāo)是為 ids
中的每個(gè)值構(gòu)建一個(gè) in (%s, %s, %s, ..., %s)
子句,其中包含一個(gè) %s
占位符。
有幾點(diǎn)需要注意:
IN
子句中的占位符數(shù)量可能有上限。有關(guān)詳細(xì)信息,請參閱 MySQL IN 條件限制。ids
為空,則此查詢無效。您可能已經(jīng)有一些邏輯來處理空 ids
列表的情況,或者您的代碼可能永遠(yuǎn)不會在 ids
為空的情況下調(diào)用。如果沒有,您將需要處理此案。