我正在寻找以下使用 Java 中准备好的语句更新 SQL 表的最佳编码模式。
SQL 表名称为 table1,table1 中为 attr1、att2、att3、att4、attr5 和 ....。
目前是我的伪
If (want to update att1 only) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?");
} else if (want to update attr1 & attr2 only) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?");
} else if (want to update attr1 & attr2 & attr3) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?");
} else if (want to udpate attr1 & attr3) {
PreparedStatement pst = Connection.prepareStatement("UPDATE table1 SET attr1 = ?, attr3 = ?");
} ......
.... else {
Bad Request
}
上面的代码会使 WHERE SQL 条件变得更加复杂。我不喜欢这里的 if - else if - else 模式,因为 非常难以维护。
是的,我知道其他选项是动态生成 UPDATE SQL 查询并使用 ORM 解决方案。 我相信动态生成SQL UPDATE 查询逻辑会变得复杂。
请提供最适合此处的任何其他模式或解决方案。
最佳答案
您可以只编写一个更新语句来更新所有非关键字段并每次调用它。
public class MyThing {
private long uniqueID;
private String attr1;
private String attr2;
private String attr3;
// ++ rest of attriutes, getters and setters
}
public MyThing getMyThing(long uniqueID) {
// code to retrieve MyThing from table1, poulating all attributes
}
public void updateMyThing(MyThing myThing) {
PreparedStatement pst = Connection.prepareStatement
(" UPDATE table1 SET attr1 = ?, attr2 = ?, attr3 = ?, attr4 = ?, attr5 = ?" +
" WHERE id = ? );
pst.SetString(1, myThing.getAttr1());
pst.SetString(2, myThing.getAttr2());
pst.SetString(3, myThing.getAttr3());
pst.SetString(4, myThing.getAttr4());
pst.SetString(5, myThing.getAttr5());
pst.SetString(6, myThing.getId());
// etc.
}
因此,从数据库中检索 MyThing 对象。更新您想要的任何属性,然后调用更新方法。所有属性均已更新,无论是否更改
关于java - 在 Java 中寻找 UPDATE SQL 的模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723801/