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);
}
相關文章
相關標籤/搜索