Prepared statement with dynamic where clause

后端 未结 3 2115
耶瑟儿~
耶瑟儿~ 2020-12-20 17:40

I have a search page with multiple search criteria

  1. Employee Name
  2. Employee Id
  3. Date of joining
  4. Department

etc

U

3条回答
  •  再見小時候
    2020-12-20 18:01

    In such conditions I prefer adding 1=1 in where clause so that you dont have to keep track of where to insert AND.

    String selectClause = "SELECT * FROM EMPLOYEES WHERE 1=1 ";
    if(StringUtils.isNotBlank(empName)){
       selectQuery += "AND EMP_NAME = " + empName;
    }
    if(StringUtils.isNotBlank(empID)){
       selectQuery += "AND EMP_ID = " + empID;
    }
    //... and so on ...
    

    Related question.

提交回复
热议问题