Java基础小案例之编写动态插入sql语句,查询sql

给出一个数组或者集合,即字段,插入给定的表。 如字段数组为: “name”, “position”, “salary” 表为:employee

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 params = new StringBuilder(1024); 
         StringBuilder postion = new StringBuilder(1024);
         for(String s: fields) {
          
   
            params.append(s+", "); 
            postion.append("?, ") ;
         }

        String s1 = params.toString();
        String s2 = postion.toString();
        System.out.println(s1);
		System.out.println(s2);
        s1 = s1.substring(0, s1.length()-2);
        s2 = s2.substring(0, s2.length()-2);

        String insertSql = "INSERT INTO %s (%s) VALUES (%s)".formatted(table,s1, s2);

    return insertSql;

    }

}

还是上面给定的条件不过这次是编写查询SQL:

public class Main {
          
   
    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) ? "测试成功" : "测试失败");
    }
    static String buildSelectSql(String table, String[] fields) {
          
   
        String s = String.join(", ", fields);
        System.out.println(s);
		String selectSql="SELECT %s FROM %s".formatted(s,table);
    return selectSql;
    }

}
经验分享 程序员 微信小程序 职场和发展