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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章