您的位置:首页 > 编程语言 > Java开发

java中对SQL模糊查询通配符%的处理

2012-07-01 15:08 441 查看
在模糊查询的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;
}


其实就是利用oracle的escape函数进行转义,把通配符转义成普通符号使用。

/**   总行数   */
String _sql = "select count(1) from ("+sql.toString()+") ";
long rowCount;

if(!StringUtils.isEmpty(keyWords)){
rowCount = courseInfoService.getCountByJdbc(_sql, map);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: