`

多条件查询时,拼接原生sql语句的方法

 
阅读更多
适用场景:
1.在一般企业的成熟开发模型中,都有自己封装好的多条件查询类,但是当我们在做一些中小型 网站或者是在学习中时,会用到自己去拼写sql语句来实现多条件查询功能。
2.即使在大型企业中有自己封装好多的多条件查询类,但那些封装好的多调价查询都是基于实体进行写的。所以,如果我们对于一个视图进行多条件查询时,就不能再次使用企业封装好的多条件查询类了,此时需要我们自己去手动拼写一个多条件查询方法。
代码:
    /*
* @author:  张齐
* @说明:  根据前台用输入的查询条件,得到一个原生查询语句
* @param  searchCondition 参数数组
* @return String 返回的原生sql语句
*/
public String getSql(String[] searchCondition){
StringBuffer sbuf = new StringBuffer("select * from v_sms_mobile");
boolean judge = false;
if(searchCondition[0]!=null&&!searchCondition[0].trim().equals("")){
sbuf.append(" where content like '%"+searchCondition[0]+"%'");
judge = true;
}
    if(searchCondition[1]!=null&&!searchCondition[1].trim().equals("")){
    if(judge){
    sbuf.append(" and description like '%"+searchCondition[1]+"%'");
    judge = false;
    }else{
    sbuf.append(" where description liek '%"+searchCondition[1]+"%'");
    judge = true;
    }
    }
    if(searchCondition[2]!=null&&!searchCondition[2].trim().equals("")){
    if(judge){
    sbuf.append(" and status ="+Integer.parseInt(searchCondition[2]));
    judge = false;
    }else{
    sbuf.append(" where status ="+Integer.parseInt(searchCondition[2]));
    judge = true;
    }
    }
if(searchCondition[3]!=null&&!searchCondition[3].trim().equals("")){
if(judge){
sbuf.append(" and mobile like '%"+searchCondition[3]+"%'");
    judge = false;
}else{
sbuf.append(" where mobile like '%"+searchCondition[3]+"%'");
    judge = true;
}
}   
if(searchCondition[4]!=null&&!searchCondition[4].trim().equals("")){
if(judge){
sbuf.append(" and sendDate like '%"+searchCondition[4]+"%'");
    judge = false;
}else{
sbuf.append(" where sendDate like '%"+searchCondition[4]+"%'");
    judge = true;
}
}
       if(searchCondition[5]!=null&&!searchCondition[5].trim().equals("")){
       if(judge){
    sbuf.append(" and code like %"+Integer.parseInt(searchCondition[5])+"%");
    judge = false;
    }else{
    sbuf.append(" where code like %"+Integer.parseInt(searchCondition[5])+"%");
    judge = true;
    }
       }
   if(searchCondition[6]!=null&&!searchCondition[6].trim().equals("")){
   if(judge){
sbuf.append(" and reportErrorCode like '%"+searchCondition[4]+"%'");
    judge = false;
}else{
sbuf.append(" where reportErrorCode like '%"+searchCondition[4]+"%'");
    judge = true;
}
   }
return sbuf.toString();

}
代码的补充说明:
1.我把多条件查询参数当成了一个String[]数组从action中往DAO层传递,其实我们也 可以直接传递VO,然后用get方法取值。
2.该逻辑复杂的就是where是不是应该有的问题,其实我们还可以改变sql语句的初始值,可以写成这样的形式select * from v_sms_mobile where 1=1;  此时再去写以上逻辑就简单的多了。
    

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics