servlet中多条件查询使用方法

时间:2020-05-22 09:21:29 类型:JAVA
字号:    

多条件查询,会有N个判断, 根据每种条件查询写方法, 会头变得越来越大, 这个时候我们可以用下面这种方法,只需分别判断单个值就ok

String names = request.getParameter("names");
String blood = request.getParameter("blood");
String search = "";
if(names != null && names != ""){
    search += " and names like '%"+names+"%' ";
}
if(blood != null && blood != ""){
    search += " and blood = '"+blood+"' ";
}
if(!search.equals("")){
    search = " where " + search.substring(4);
    System.out.println(search);
}

String sql = "select * from students " + search + " order by id desc";
//最终可生成结果
//where  names like '%小红%'  and blood = 'AB'


<