java高级查询_SQL高级查询

public classSqlCondition {//职位:用于查询的条件判断

privateString title;//职位类型:用于查询的条件判断

privateInteger positiontype;publicSqlCondition() {super();

}publicString getTitle() {returntitle;

}public voidsetTitle(String title) {this.title =title;

}publicInteger getPositiontype() {returnpositiontype;

}public voidsetPositiontype(Integer positiontype) {this.positiontype =positiontype;

}/*** 查询语句的条件判断

* 方法一(推荐使用):*/

publicString getQueryCondition_01(){

String whereSql="";if(title !=null && !"".equals(title)){

whereSql+= " and title like '%"+title+"%'";

}if(positiontype!=null && !"".equals(positiontype)){

whereSql+=" and positiontype = "+positiontype;

}//replace:替换;First:第一个

return whereSql.replaceFirst("and", "where");

}/*** 查询语句的条件判断

* 方法二(不推荐使用): where 1==1 会影响查询的性能*/

publicString getQueryCondition_02(){

String whereSql= "where 1==1";if(title != null && !"".equals(title)){

whereSql+= "and title like '%"+title+"%'";

}if(positiontype !=null){

whereSql+= "and positiontype = " +positiontype;

}returnwhereSql;

}/*** 查询语句的条件判断

* 方法三(准备一个标识(即一个flag)

如果标识是true,条件前就加where,如果是false,条件前就加and):*/

publicString getQueryCondition_03(){//标识:flag

boolean flag = true;

String whereSql= "";//title不为null,并且不为空字符串

if(title!=null && !"".equals(title)){if(flag){

whereSql+= " where ";

flag= false;

}else{

whereSql+= " and ";

}

whereSql+= " title like '%"+title+"%' ";

}if(positiontype!=null){if(flag){

whereSql+= " where ";

flag= false;

}else{

whereSql+= " and ";

}

whereSql+= " positiontype = "+positiontype;

}returnwhereSql;

}/*** 查询语句的条件判断

* 方法四(准备一个集合):*/

publicString getQueryCondition_04(){//准备一个集合(里面会装咱们的所有条件)

List sqlList = new ArrayList<>();

String whereSql= "";//title不为null,并且不为空字符串

if(title!=null && !"".equals(title)){

sqlList.add(" title like '%"+title+"%' ");

}if(positiontype!=null){

sqlList.add(" positiontype = "+positiontype);

}//查询条件加多了,只要在这加if语句就可以了//遍历这个集合

for (int i = 0; i < sqlList.size(); i++) {if(i==0){//第一次循环,前面肯定是加where

whereSql += " where ";

}else{//第2-n次循环,前面肯定是加and

whereSql += " and ";

}

whereSql+=sqlList.get(i);

}returnwhereSql;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值