Like fuzzy query input % or _ solution to query all records

background:

Fuzzy query was used in a recent project. During the test, the tester found that when the front-end query condition text box was entered with a % or _, all records were queried. However, the field values ​​stored in the database for this query condition do not include % or _, which is obviously a bug.

analyze:

It turns out that % or _ have special meaning in sql

% (percent sign): equivalent to any number of characters;

_ (underscore): equivalent to any single character;

Solution:

1. The background obtains the content of the query condition box passed in and replaces % and _

2. The sql statement specifies an uncommon escape character.

 

Code behind :

// qryCondition是前段的查询条件框录入的内容

//转义%
if(qryCondition.contains("%")){
    qryCondition = qryCondition.replaceAll("%","/%");
}


//转义_
if(qryCondition.contains("_")){
    qryCondition = qryCondition.replaceAll("_","/_");
}

Modify sql[ mybatis ] to specify the escape character/

select * from tab_test where userName like '%' || #{qryCondition} || '%'   escape   '/' 

 

Guess you like

Origin blog.csdn.net/dhklsl/article/details/115631101