Discuss / Java / 作业

作业

Topic source
public class StringBuilderTest {    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 fileds[]) {        StringBuilder builder = new StringBuilder(100);        String[] strings = new String[4];        int[] ints = new int[4];        builder.append(table);        ints[0] = builder.length();        for (int i = 0; i < fileds.length; i++) {            builder.append(fileds[i]);            ints[i + 1] = builder.length();        }        for (int i = 0; i < ints.length; i++) {            if (i == 0) {                strings[i] = builder.substring(0, ints[i]);            } else {                strings[i] = builder.substring(ints[i - 1], ints[i]);            }        }        return String.format("INSERT INTO %s (%s, %s, %s) VALUES (?, ?, ?)", strings[0], strings[1], strings[2], strings[3]);    }}

  • 1

Reply