Discuss / Java / 第二种方法。关注微信公众号【程序员明明】

第二种方法。关注微信公众号【程序员明明】

Topic source

明明love0

#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);
		System.out.println(
				"INSERT INTO employee (name, position, salary) VALUES (?, ?, ?)".equals(insert) ? "测试成功" : "测试失败");
	}

	static String buildInsertSql(String table, String[] fields) {
		StringBuilder stringBuilder = new StringBuilder();
       //	stringBuilder.append("INSERT INTO " + table + " (" + fields[0] + ", " + fields[1] + ", " + fields[2] + ") VALUES (?, ?, ?)");

	    stringBuilder.append("INSERT INTO " + table + " (");
	    for (int i = 0; i < fields.length; i++) {
	        stringBuilder.append(fields[i]).append(", ");
	    }
	    stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length());
	    //上一句用于减去结尾多加的“, ”
	    stringBuilder.append(") VALUES (?, ?, ?)");
	    return stringBuilder.toString();
	}

}


  • 1

Reply