Discuss / Java / 练习题

练习题

Topic source

唯情恋昉

#1 Created at ... [Delete] [Delete and Lock User]

练习作答

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) {
        // 第一种写法
        // return "INSERT INTO " + table + " (" + String.join(", ", fields) + ") " + "VALUES (?, ?, ?)";
        // 第二种写法
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO ")
          .append(table)
          .append(" (")
          .append(String.join(", ", fields))
          .append(") ")
          .append("VALUES (?, ?, ?)");
        return sb.toString();
    }
}

  • 1

Reply