How to fill a query sql with multiple optional parameter in PreparedStatement?

后端 未结 1 663
余生分开走
余生分开走 2021-01-13 04:25

I explain myself...

I have a form with fill the query (eg.):

SELECT * 
FROM table 
WHERE id=? AND name=? AND sex=? AND year=? AND class=?

相关标签:
1条回答
  • 2021-01-13 05:21

    You'd either have to use multiple prepared statements or just create a statement on the fly, checking which parameters you have.

    Like this:

    String query = "SELECT * FROM table WHERE id=?";
    if( nameParameter != null ) {
      query += " AND name=?"; //don't never ever directly add the value here
    }
    ...
    

    Update/Warning: Don't directly add the parameter values to the query string but use PreparedStatement and the like instead. As displayed above the query string should only contain placeholders for the values (eg. ?) in order to prevent SQL-injection attacks.

    What I mean is, do NOT do the following:

    if( nameParameter != null ) {
      //NEVER EVER, REALLY I MEAN IT, DON'T DO THIS
      query += " AND name='" + nameParameter + "'"; 
    }
    
    0 讨论(0)
提交回复
热议问题