sql查询不定参数生成where子句不定参数查询

来源:互联网 发布:centos nginx 根目录 编辑:程序博客网 时间:2024/06/05 18:20

生成where语句的工具类生成形式如: where name = 'xx' and password = 'xx' 参数是不定的,可以一个参数,也可以二个参数

package util;import java.util.HashMap;import java.util.Map;/** * where语句工具类 * */public class StringWhere {//写一个方法,进去的是参数,出来的是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 ");// 遍历有参数得mapfor (Map.Entry<String, String> entry : mw.entrySet()) {where.append(entry.getKey()+"= '"+entry.getValue()+"'");i++;//如果是最后一个字段条件则不添加andif(i!= mw.size()) {where.append(" and  ");}}System.out.println("where字符串为:"+where);return where.toString();}return where.toString();}return where.toString();}}

例如:

String username = "user";
String password = "password";
Map<String, String> map = new HashMap<String, String>();
map.put("username", username);
map.put("password", password);
String where = StringWhere.getWhere(map);

得到的结果是 where username = 'user' and password = 'password'

如果String username = ""; 则结果为: where password = 'password'

这样就能实现不定参数的where子句获取!

0 0
原创粉丝点击