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