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

在模糊查询的SQL语句中,若是有用户输入查询通配符‘%’,使用 select * from table where code like '%condition%'的SQL,会查出所有记录,这个如何解决叱?java

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函数进行转义,把通配符转义成普通符号使用。sql

/**   总行数   */
		String _sql = "select count(1) from ("+sql.toString()+") ";
		long rowCount;
	
		if(!StringUtils.isEmpty(keyWords)){
			rowCount = courseInfoService.getCountByJdbc(_sql, map);
}
相关文章
相关标签/搜索