我想创建一个包含多个set子句的update语句。问题是这些参数中的一些可以为null(不是全部)。我需要在这些陈述之前加上一些逗号,但我不知道如何有效地处理这个问题。有没有办法做到这一点?
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
这是我的功能;
public static void update(value1, value2, value3){
String sql = "UPDATE table SET ";
//I need to check if these values are not null then I need to add them to sql string.
sql += " WHERE condition";
}
我的解决方案;
int count = 0;
if(value1 != null){
if(count == 0) {
sql += "column1 = value1";
} else {
sql += ", column1 = value1";
}
count++;
}
if(value2 != null){
if(count == 0) {
sql += "column2 = value2";
} else {
sql += ", column2 = value2";
}
count++;
}
if(value3 != null){
if(count == 0) {
sql += "column3 = value3";
} else {
sql += ", column3 = value3";
}
count++;
}
答案 0 :(得分:1)
尝试使用地图,其中键是列名,值是列值,如下所示:
public static String addSetValue(Map<String, Object> fieldMap) {
StringBuilder setQueryPart = new StringBuilder();
for (Map.Entry<String, ? extends Object> entry: fieldMap.entrySet()) {
if (entry.getValue() != null){
setQueryPart.append(entry.getKey() + " = " +entry.getValue() + ", ");
}
}
//Remove last comma, since we don't need it.
setQueryPart.deleteCharAt(setQueryPart.lastIndexOf(","));
return setQueryPart.toString();
}
然后,您只需传递先前填充的地图,并将返回字符串附加到查询字符串。
答案 1 :(得分:1)
首先,创建一个快速Bean来存储键值
class Token{
private String key, value;
public Token(String key, String value) {
this.key = key;
this.value = value;
}
}
然后使用Stream
来:
Token
快速测试:
List<Token> list = new ArrayList<>();
list.add(new Token("A", "Foo"));
list.add(new Token("B", null));
list.add(new Token("C", "Bar"));
String query =
String.join(",",
list.stream()
.filter(t -> t.value != null)
.map(t -> t.key + "=" +t.value)
.toArray(String[]::new)
);
System.out.print(query);
A =美孚,C =酒吧
与PreparedStatement
一起使用的其他解决方案:
//remove every null values
list.removeIf(t -> t.value == null);
//Build the query with parameters ?
query =
String.join(",",
list.stream()
.filter(t -> t.value != null)
.map(t -> t.key + "=?")
.toArray(String[]::new)
);
System.out.println(query);
A =?,C =?
列表中有相应的参数。