如何在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
相关产品推荐
相关产品推荐

