多条件查询时,拼接原生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; 此时再去写以上逻辑就简单的多了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值