Discuss / Java / 练习

练习

Topic source
/** * 使用StringJoiner构造一个SELECT语句 */

public class StringJoinerDemo2 {
    public static void main(String[] args) {

        String[] fields = { "name", "position", "salary" };
        String table = "employee";
        String select = buildSelectSql(table, fields);
        System.out.println(select);
        System.out.println("SELECT name, position, salary FROM employee".equals(select) ? "测试成功" : "测试失败");
    }

    private static String buildSelectSql(String table, String[] fields) {
        StringBuilder sb = new StringBuilder(512);
        StringJoiner sj = new StringJoiner(", ", "SELECT ", " FROM ");
        for (String name:fields){
            sj.add(name);
        }
        sb.append(sj).append(table);

        return sb.toString();
    }
}


  • 1

Reply