我尝试在 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))
这不会给出错误,但不起作用。
有什么建议吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您可以将 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))此处的目标是为
ids中的每个值构建一个in (%s, %s, %s, ..., %s)子句,其中包含一个%s占位符。有几点需要注意:
IN子句中的占位符数量可能有上限。有关详细信息,请参阅 MySQL IN 条件限制。ids为空,则此查询无效。您可能已经有一些逻辑来处理空ids列表的情况,或者您的代码可能永远不会在ids为空的情况下调用。如果没有,您将需要处理此案。