Mybatis的sql语句中下划线_,百分号%的转义处理---escape的作用【转】


源地址:https://blog.csdn.net/yh869585771/article/details/80276437

综述

        在使用LIKE关键字进行模糊查询时,“%”、“_”和“[]”单独出现时,会被认为是通配符。为了在字符数据类型的列中查询是否存在百分号 (%)、下划线(_)或者方括号([])字符,就需要有一种方法进行转义

思路

解决办法---使用ESCAPE定义转义符

 

        在使用LIKE关键字进行模糊查询时,“%”、“_”和“[]”单独出现时,会被认为是通配符。为了在字符数据类型的列中查询是否存在百分号 (%)、下划线(_)或者方括号([])字符,就需要有一种方法告诉DBMS,将LIKE判式中的这些字符看作是实际值,而不是通配符。关键字 ESCAPE允许确定一个转义字符,告诉DBMS紧跟在转义字符之后的字符看作是实际值。

如下面的表达式:

        LIKE '%M%' ESCAPE ‘M' 

        使用ESCAPE关键字定义了转义字符“M”,告诉DBMS将搜索字符串“%M%”中的第二个百分符(%)作为实际值,而不是通配符。当然,第一个百分符(%)仍然被看作是通配符,因此满足该查询条件的字符串为所有以%结尾的字符串。
类似地,下面的表达式:

        LIKE  'AB&_%'   ESCAPE  ‘&'

        此时,定义了转义字符“&”,搜索字符串中紧跟“&”之后的字符,即“_”看作是实际字符值,而不是通配符。而表达式中的“%”,仍然作 为通配符进行处理。该表达式的查询条件为以“AB_”开始的所有字符串。

实例

escape 是sql中的关键字,定义转义字符。如下:

SELECT * FROM student t where t.name like '%/%' escape '/';执行结果为:

SELECT * FROM student t where t.name like '%%' escape '/';执行结果为:

 

注:

由此可见,escape '/' 是指用'/'说明在/后面的字符不是通配符,而是普通符。

即第一个sql语句中的第二个%是普通字符,找的是最后一个字符为%的名字的记录。

 

 扩展

 

  • mybatis like 模糊查询的集中常见方式

 

1.  参数中直接加入%%

  param.setUsername("%CD%");
      param.setPassword("%11%");

    <select  id="selectPersons" resultType="person" parameterType="person">
        select id,sex,age,username,password from person where true 
            <if test="username!=null"> AND username LIKE #{username}</if>
            <if test="password!=null">AND password LIKE #{password}</if>
    
    </select>

2.  bind标签

    <select id="selectPersons" resultType="person" parameterType="person">
        <bind name="pattern" value="'%' + _parameter.username + '%'" />
        select id,sex,age,username,password 
        from person
        where username LIKE #{pattern}
    </select>

3. CONCAT

    where username LIKE concat(concat('%',#{username}),'%')

mybatis 中不同数据库的sql拼接方式

<if test="companyName != null and companyName != ''">  
   AND a.company_name LIKE   
   <if test="dbName == 'oracle'">'%'||#{companyName}||'%' ESCAPE '/'</if>  
   <if test="dbName == 'mssql'">'%'+#{companyName}+'%'</if>  
   <if test="dbName == 'mysql'">concat('%',#{companyName},'%')</if>  
</if>  

 

    <select id="getUsersCount" resultType="java.lang.Integer">
        select count(1) from user
        <if test="key != null and key !='' ">
            <bind name="pattern_key" value="'%' + key + '%'" />
            where name LIKE #{pattern_key} ESCAPE '/'
        </if>
    </select>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM