请使用StringBuilder构造一个INSERT语句:
public class Main {
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) {
// TODO:使用StringBuilder拼接字符串
StringBuilder s=new StringBuilder();
s.append("INSERT INTO ");
s.append(table);
s.append(" (");
for (int i = 0; i < fields.length; i++) {
if (i < fields.length - 1) {
s.append( fields[i] + ", " );
} else {
s.append( fields[i] );
}
}
s.append(") VALUES (?, ?, ?)");
return s.toString();
}
}
还可以使用StringJoiner,可以发现使用StringJoiner后代码简化了很多
语法:StringJoiner s=new StringJoiner(间隔符,指定开头字符串(可省),指定结尾字符串(可省))
import java.util.StringJoiner;
public class Main {
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) {
// TODO:使用StringJoiner拼接字符串
StringJoiner sj = new StringJoiner(", ","INSERT INTO "+table+" (",") VALUES (?, ?, ?)");
for (String field : fields) {
sj.add(field);
}
return sj.toString();
}
}
String.join():String还提供了一个静态方法join(),这个方法在内部使用了StringJoiner来拼接字符串,在不需要指定“开头”和“结尾”的时候,用String.join()更方便:
public class Main {
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) {
// TODO:使用String.join和StringBuilder拼接字符串
String s = String.join(", ", fields);
StringBuilder sd = new StringBuilder();
sd.append("INSERT INTO "+table+" (");
sd.append(s);
sd.append(") VALUES (?, ?, ?)");
return sd.toString();
}
}
所有博客均为自己学习的笔记。如有错误敬请理解。