Discuss / Java / 练习

练习

Topic source

Lumen.

#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) {

        StringBuilder sb =new StringBuilder();

        sb.append("INSERT INTO ").append(table).append(" (");

            for(int i=0;i<=fields.length-1;i++){

                sb.append(fields[i]);

                if(i< fields.length-1){

                    sb.append(", ");

                }

            }

        sb.append(") VALUES (");

            for(int i=0;i<=fields.length-1;i++){

                sb.append("?");

                if(i< fields.length-1){

                    sb.append(", ");

                }

            }

        return sb.append(")").toString();

    }

}

Lumen.

#2 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) {
        StringBuilder sb =new StringBuilder();
        sb.append("INSERT INTO ").append(table).append(" (");
        for (String n : fields){
            sb.append(n+", ");
        }
        sb.append(')').append(" VALUES (?, ?, ?)");
        return sb.toString().replace(", )", ")");
    }
}

  • 1

Reply