SQL查询时,参数个数不定时,自动过滤select语句where
//写一个方法,进去的是参数,出来的是where a = ? and b = ?的形式
//只针对字段全部是String类型
public static String getWhere(Map<String, String> map) {
StringBuffer where = new StringBuffer();
//如果map不为空
if(map.size()>0) {
Map<String, String> mw = new HashMap<String, String>();
//解析Map,如果map中的值不为空则放入新的map中
for(Map.Entry<String, String> entry: map.entrySet()) {
if(entry.getValue()!=null&&!entry.getValue().equals("")) {
mw.put(entry.getKey(), entry.getValue());
}
}
//定义一个制位符判断添加最后一个字段不添加and的
int i = 0;
if(mw.size()>0) {
where.append("where ");
// 遍历有参数得map
for (Map.Entry<String, String> entry : mw.entrySet()) {
where.append(entry.getKey()+"= '"+entry.getValue()+"'");
i++;
//如果是最后一个字段条件则不添加and
if(i!= mw.size()) {
where.append(" and ");
}
}
System.out.println("where字符串为:"+where);
return where.toString();
}
return where.toString();
}
return where.toString();
}
本文介绍了一种根据传入的参数动态生成SQL WHERE子句的方法。该方法适用于所有字段类型为String的情况,并能自动过滤掉空值或空白字符串参数,确保生成的SQL语句正确且高效。
3214

被折叠的 条评论
为什么被折叠?



