首页  >  问答  >  正文

在带有参数的 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 天前386

全部回复(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
  • 取消回复