问题:在模糊查询的SQL语句中,如果有用户输入查询通配符‘%’,使用 select * from table where code like '%condition%'的SQL,会查出全部记录,这个如何解决?
if(!StringUtils.isEmpty(_cname)){
/** 处理模糊通配符%和_ */
sql.append(" and c.FCOURSEWARE_NAME LIKE '%").append(EscapeUtils.escapeStr(_cname)).append("%' escape '\\'");
model.addAttribute("_cname", _cname);
}
EscapeUtils的escapeStr方法:(注意:只能屏蔽已‘%'或'_'开始或结尾的字符串)
/**
* Description: 处理转义字符%和_,针对ORACLE数据库
* @param str
* @return
*/
public static String escapeStr(String str){
if(str.startsWith("%") || str.startsWith("_")){
str = "\\" + str;
}
if(str.endsWith("_")){
int index = str.indexOf("_");
str = str.substring(0, index) + "\\" + "_";
}
if(str.endsWith("%")){
int index = str.indexOf("%");
str = str.substring(0, index) + "\\" + "%";
}
return str;
}
屏蔽字符串中的任意位置%'或'_' ,针对Oralce数据库:
public String escapeStr(String str){
String temp = "";
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '%' || str.charAt(i) == '_') {
temp += "\\" + str.charAt(i);
} else {
temp += str.charAt(i);
}
}
if (temp.contains("%") || temp.contains("_")) {
temp = "'%" + temp + "%' escape '\\'";
} else {
temp = "'%" + temp + "%'";
}
return temp;
}