You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQLAlchemy原生SQL的LIKE '%STRING%'中绑定参数?

如何在SQL LIKE语句中使用参数化查询?

你的问题出在把参数占位符和通配符%放在了同一个字符串常量里,数据库没识别出:String是参数,反而把它当成普通字符串内容去匹配,自然查不到结果。下面给两种可行的解决方法:

方法1:在Python中拼接通配符和参数值

先把搜索内容和前后的%拼接好,再作为参数传入SQL,确保占位符能被正确解析:

search_str = 'hello world'
# 提前拼接通配符与搜索内容
param_value = f'%{search_str}%'

my_query = '''
    select *
    from my_table
    where exists (
        select
        from unnest(procedure) elem
        where elem like :param_value
              )
    '''

result = connection.execute(text(my_query), param_value=param_value)

方法2:在SQL语句内用字符串连接组合通配符和参数

不同数据库的字符串连接语法有差异,比如PostgreSQL用||,MySQL用CONCAT(),这里以PostgreSQL为例:

search_str = 'hello world'

my_query = '''
    select *
    from my_table
    where exists (
        select
        from unnest(procedure) elem
        where elem like '%' || :search_str || '%'
              )
    '''

result = connection.execute(text(my_query), search_str=search_str)

两种方法都能保证参数被正确替换,同时保留参数化查询的安全性(避免SQL注入),你可以根据使用的数据库选择对应方式。

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:30:59