Prepared statement with dynamic where clause

后端 未结 3 2095
耶瑟儿~
耶瑟儿~ 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 17:50

    I wouldn't like using a StringBuilder to dynamically create a query each and every time, especially when the number of meaningful combinations is countable and finite.

    I'd always prefer static Strings. Yes, you have to type them in, but you'll do that once. I'd rather do that than pay the price in complexity and at runtime.

    0 讨论(0)
  • 2020-12-20 17:59

    This is easy to do without any complex or expensive logic, in a single line...

    Assuming that your three variables are @name, @surname, and @gender.

    Also assuming that a zero-length string will be provided when a filter is not required.

    Then, your Select statement is simply:

        select * from table_name where (name = @name or @name = '') and (surname = @surname or @surname = '') and (gender = @gender or @gender = '')
    

    That's all there is to it! No complex or expensive logic.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题