Discuss / Java / solution

solution

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) {
    	String[] placeholders=new String[fields.length];
    	for (int i = 0; i < fields.length; i++) {
    		placeholders[i]="?";
		}
    	
    	StringBuilder stringBuilder=new StringBuilder();
    	stringBuilder.append("INSERT INTO ")
    				 .append(table)
    				 .append(" (")
    				 .append(String.join(", ", fields))
    				 .append(")")
    				 .append(" VALUES (")
    				 .append(String.join(", ", placeholders))
    				 .append(")");
        return stringBuilder.toString();
    }

}

  • 1

Reply