如果使用ugliness算作“没有 if-else”:
String[] fields = {"par1","par2","par3"};
String query = "SELECT * FROM TABLE t ";
String where = "";
String[] whereString = new String[]{" WHERE ", " AND "};
int whereAddress = 0;
List<String> valuesAsParameters = new ArrayList<String>();
for(String fieldName : fields) {
String value = request.getParameter(fieldName);
//do we need WHERE or AND?
where += whereString[whereAddress];
whereAddress=1; //change state
where += fieldName;
//should not EVER use exception for control flow... Outside of assignments, that is
try {
//throws NPE **on purpose**... Yuck!!!
valuesAsParameters.add(value.toString());
// to check emptiness of string, we could use value.charAt(0) for the same purpose
where += " = ? ";
} catch(NullPointerException e) {
// EEEEEEKKKK! No, please really, don't do stuff like this...
// I shall burn in hell for even
// thinking about
// **thinking about**
// ****thinking about****
// something this unexplainably, and universally bad...
where += " IS NULL ";
}
}
Connection conn = DataBase.getConnection();
PreparedStatement s = conn.prepareStatement(query);
int i=1;
for(String value : valuesAsParameters) {
s.setString(i++, value);
}
打扰一下,我现在得去吐了……这代码纯属邪恶。这里是龙不要在家里这样做。我所说的家是指宇宙中已知和未知的部分。包括未知的维度,不存在的地方,甚至梦想……我想 我已经开始看到摇摆不定的东西了……
编辑
好的,现在好多了。然而,上面的代码并没有做 OP 想要的,虽然很容易定制它。这样做是对空值使用 IS NULL 子句,就像在 SQL 中一样,这是将某些东西与null
.