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

生成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 ");
				// 遍历有参数得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();
	}
	
}

 例如: 

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子句获取!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值