StringBuilder 小练习实现方法一

`public class Demo12 {
public static void main(String[] args) {
String[] fields = { "name", "position", "salary" };
String table = "employee";
String insert = buildInsertSql(table, fields);
System.out.println(insert);
String s = "INSERT INTO employee (name, position, salary) VALUES (?, ?, ?)";
System.out.println(s.equals(insert) ? "测试成功" : "测试失败");
}
static String buildInsertSql(String table, String[] fields) {

StringBuilder sb = new StringBuilder(1024);
sb.append("INSERT INTO "+ table + " (");

//for循环来拼接数组元素的字符串
for(int i=0;i<fields.length;i++){
if(i != fields.length-1){
sb.append(fields[i]+", ");
}else{
sb.append(fields[i]);
}
}

sb.append(") VALUES (?, ?, ?)");

return sb.toString();
}

}`

posted @ 2020-12-23 14:26  dog_IT  阅读(131)  评论(0)    收藏  举报