天天看點

JAVA拼接多條件SQL查詢

在開發的過程中,我們可能需要大量的從資料庫查詢資料進行互動;很常見的查詢邏輯,where後面的條件是多個需要拼接的;

這裡提供一個基本案例;

private void initUserCodeMap(Set users){

String wherecondtion=processArrayToString(users);

String orgsql=“select cuserid, user_code from sm_user where cuserid in “+wherecondtion;

try {

this.userCodeMap.clear();

ArrayList list= (ArrayList) getquerybs().executeQuery(orgsql, new ArrayListProcessor() );

for(int i=0;i<list.size();i++){

Object[] o=(Object[]) list.get(i);

String pk_stordoc=(String)o[0];

String code=(String)o[1];

this.userCodeMap.put(pk_stordoc, code);

}

} catch (BusinessException e) {

e.printStackTrace();

}

}

這是對查詢的結果集放在map中處理,查詢多個值的Set對象處理結果集的多個對象;

下面是對查詢條件的SQL拼接

private String processArrayToString(Set attr){

if(attr==null||attr.isEmpty()){

return “”;

}

StringBuffer sb=new StringBuffer();

sb.append(”(”);

for (String str:attr){

sb.append("’");

sb.append(str);

sb.append("’");

sb.append(",");

}

String str=sb.substring(0, sb.length()-1);

str=str+")";

return str;

}

這裡的參數類型需要初始化private Setusers=new HashSet();

簡單的實作多參數的SQL查詢;可以作為基本工具類使用;

繼續閱讀