日期:2014-05-16  浏览次数:20431 次

处理转义字符%和_,针对ORACLE数据库

?

public class EscapeUtils {
	public static String escapeStr(String str){
		if(str.startsWith("%") || str.startsWith("_")){
			str = "\\" + str;
		}
		if(str.startsWith("'")){
			str=str.substring(1, str.length());
		}
		if(str.endsWith("_")){
			int index = str.indexOf("_");
			str = str.substring(0, index) + "\\" + "_";
		}
		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;
	}
	
	public static void main(String[] args) {
		String queryCondition = "全国测试";
		//演示使用
		StringBuffer sb = new StringBuffer();
		if(StrUtil.isNotNull(queryCondition)){
			/**  处理模糊通配符%和_  */
			sb.append("and s.name like '%").append(EscapeUtils.escapeStr(queryCondition)).append("%' escape '\\'");
		}
		System.out.println(sb.toString());
	}
}

?

?