天天看点

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查询;可以作为基本工具类使用;

继续阅读