使用StringBuilder将字符串连接在一起。(技术上可以使用 String 对象,并使用 + 运算符将它们连接在一起,但这有很多缺点......)
String input[] = request.getParameterValues("checkbox");
StringBuilder sb = new StringBuilder(); // create empty StringBuilder instance
for(int i=0;i<input.length;i++) {
sb.append(input[i]); //append element
if (i==input.length-1) {
sb.append(" "); //append space
} else {
sb.append(", "); //append comma
}
}
String result = sb.toString();
Systemout.println(result);
或者您可以使用 StringBuilder 对象构建(参见 Builder 模式)整个查询,每个部分都有方法(addFields(StringBuilder sb)
, addFromPart(StringBuilder sb)
, addWhereClause(StringBuilder sb)
),瞧,您拥有一个小型数据访问框架的内部......
public abstract class MyQueryBuilder {
protected abstract void addFields(StringBuilder sb);
protected abstract void addFromPart(StringBuilder sb);
protected abstract void addWhereClause(StringBuilder sb);
public final String getQuery() {
StringBuilder sb = new StringBuilder();
sb.append("SELECT ");
addFields(sb); //this adds the fields to be selected
sb.append(" FROM ");
addFromPart(sb); //this adds the tables in the FROM clause
addWhereClause(sb); //this adds the where clause
//...etc
return sb.toString();
}
}