我有一个更新 MySQL 表的函数。我需要根据参数是否存在对字段进行选择性更新。这就是我现在编码的方式。
String sql = "";
if (employerId > 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 > 0) ps.setInt(1, employerId);
if (status != null) ps.setString(2,status);
当我这样做时,如何确定参数索引?根据存在的参数(如果条件),参数索引也会有所不同,对吧?我该如何解决这个问题?有没有更好的方法在 Java 中处理这个问题?