title: The proper way to prepare a dynamic Statement in Java
body: <p>I am preparing a SQL statement from values passed through a query string. ( I am using the Play! framework. Basically what I'm running into (not really an issue just something I don't like very much) is that when I want to use <code>?</code> in the SQL string and set them later with dynamic values.</p>
  
  <p>This is what I have:</p>
  
  <pre><code>String sql = "SELECT * FROM foobar_table WHERE";
  
  if ( foo != 0 )
      sql += " AND foo=?";
  if ( !bar )
      sql += " AND bar=?";
  
  try{
      PreparedStatement getStmt = con.prepareStatement(sql);
      if ( foo != 0 )
          getStmt.setInt(1,foo);
      if ( foo != 0 && !bar )
          getStmt.setBoolean(2, bar);
      else
          getStmt.setBoolean(1, bar);
  } catch (SQLException e ){
      e.printStackTrace();
  }</code></pre>
  
  <p>This does work but as you can see not very intuitive. It's OK when there are 2 dynamic values but when you get up to 5 or 6 this would just get ridiculous. </p>
  
  <p>Is there an easier way of doing this to make it more flexible so that I would know how to fill in all the <code>?</code> in a better fashion?</p>