title: Selective update using Prepared Statement
body: <p>I have one function which updates a MySQL table. I need to do a selective update of fields according to whether the parameters are present or not. This is how I have coded it right now. </p>
  
  <pre><code>        String sql =  "";
          if (employerId &gt; 0) sql = sql + "employerid=?,";
          if (status != null) sql += " status=?,";
          if(printurl != null) sql += " url=?";
          if (sql.endsWith(",")) sql = sql.substring(0, sql.length()-1);
          PreparedStatement ps = con.prepareStatement("update employer set "
                  + sql
                  + "where id=?");
  
         if (employerId &gt; 0) ps.setInt(1, employerId);
         if (status != null) ps.setString(2,status);
  </code></pre>
  
  <p>When I do like this, how do I determine the parameter index? According to the parameters present (if conditions), the parameter index will also vary, right? How do I get around with this? Is there a better way to handle this in Java?</p>