我有一个更新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中有没有更好的方法来处理这个问题呢?
发布于 2012-10-17 11:04:32
你能试一下下面的静态查询吗?
String sql = "update employer set employerid=IF(?=0,employerid,?),"+
"status=IFNULL(?,status), url=IFNULL(?,url) " +
"where id=?";从概念上讲,如果列是0或null,我建议用它本身来更新列。这样,您就不需要创建动态查询字符串或动态设置参数。
发布于 2012-10-17 10:47:12
SQL库提供了一种更好的方法来在java程序中生成动态SqlBuilder查询。QueryPreparer类通过跟踪索引来专门解决您在这里遇到的问题。
免责声明,我是SqlBuilder项目的主要开发人员。
发布于 2012-10-17 11:11:43
使用arraylist怎么样?第一次检查参数是否存在时,添加到arraylist。之后,迭代数组列表并设置参数。在这种情况下,
不仅可以确定参数的索引,还可以避免重复检查参数的存在。
就像这样
List paramList = new ArrayList<Object>();
if (employerId > 0) {
sql = sql + "employerid=? ,";
paramList.add(employerId);
}
if (status != null) {
sql += " status=? ,";
paramList.add(status);
}
if(printurl != null) {
sql += " url=? ";
paramList.add(printurl);
}
if (sql.endsWith(","))
sql = sql.substring(0, sql.length()-1);
PreparedStatement ps = con.prepareStatement("update employer set " + sql + "where id=?");
for(int i=0; i< paramList.size(); i++) {
if(paramList.get(i) instanceof Integer) {
ps.setInt((i + 1), (Integer)paramList.get(i));
}
else if(paramList.get(i) instanceof String) {
ps.setString((i + 1), (String)paramList.get(i));
}
}
System.out.println(ps);https://stackoverflow.com/questions/12926277
复制相似问题