数据库模糊搜索时,都知道应该用通配符%号来模糊匹配。如:select *from table where content like '%key%'。但当关键字key中也包含有%号时,应该怎么办?
数据库中有关键字:escape就是用来转换的。使用escape关键字定义转义符时,当转义符置于通配符之前时,该通配符就解释为普通字符。用法:ESCAPE 'escape_character' 其允许在字符串中搜索通配符而不将其作为通配符使用。'escape_character'通常用'/'或'\'做为转义符,其它如‘!'等也可以做为转义符。
示例:
select *from table where content like '%/%%' escape '/'
/为转义字符,第二个%为普通字符,第一、三个%为通配符。
select *from table where content like '%/%//%' escape '/'
/为转义字符,第二个%为普通字符,第一、三个%为通配符,第二个/为转义字符,第三个/为普通字符。
----------转载http://www.cnblogs.com/joinclear/archive/2013/02/25/2932842.html
if(StringUtils.isNotEmpty(param.getCode())){
hql.append("and node.code like ? escape ? ");
params.put(String.valueOf(params.size()), "%" + Common.getSqlLikeEscapeStr(param.getCode()) + "%");
params.put(String.valueOf(params.size()), Constants.CON_SQL_LIKE_ESCAPE);
}
public static String getSqlLikeEscapeStr(String str){
str = str.replaceAll("/", "//");
str = str.replaceAll("%", "/%");
str = str.replaceAll("_", "/_");
return str;
}