MySql的like语句中的通配符:百分号、下划线和escape
%代表任意多个字符
select * from user where username like '%huxiao'; select * from user where username like 'huxiao%'; select * from user where username like '%huxiao%';
_代表一个字符
select * from user where username like '_'; select * from user where username like 'huxia_'; select * from user where username like 'h_xiao';
如果我就真的要查%或者_,怎么办呢?使用escape,转义字符后面的%或_就不作为通配符了,注意前面没有转义字符的%和_仍然起通配符作用
select username from gg_user where username like '%xiao/_%' escape '/'; select username from gg_user where username like '%xiao/%%' escape '/';
个人开发实例:
/**
* 根据查询条件分页查询广告包信息-广告包管理
*
* @param adPackageName
* @param pageSize
* @param pageNum
* @return
*/
@SuppressWarnings("unchecked")
public List<Map<String, Object>> listAllAdByPage(String adPackageName,
int pageSize, int pageNum) {
StringBuffer sbHQL = new StringBuffer(256);
sbHQL.append(" from AdPackage as P ");
sbHQL.append(" ,AdTemplate as T ");
sbHQL.append(" where P.adTemplateId = T.adTemplateId ");
sbHQL.append(" and P.dataStat = " + Constant.DATA_STAT_ON);// 选择0-有效数据
List<Object> params = new ArrayList<Object>();
setQueryCondition(adPackageName, sbHQL, params);
sbHQL.append(" order by P.adPackageCreaterTime desc");
return getHibernateTemplate().executeFind(
new QueryByHqlWithHibernateCallBack(sbHQL.toString(), params,
pageNum, pageSize));
}
/**
* 设置广告包管理模块查询条件
* 20130826 查询”_“处理
* @param adPackageName
* @param sbHQL
* @param params
*/
private void setQueryCondition(String adPackageName, StringBuffer sbHQL,
List<Object> params) {
if (!StringUtils.isEmpty(adPackageName)) {
sbHQL.append(" and P.adPackageName like ? escape '/'");
params.add("%" + adPackageName.trim().replaceAll("_", "/_") + "%");
}
}