JavaBean的list集合拼接成Insert语句

时间:2025-02-15 16:58:34

最近工作可恶心了,整的框架不让用,还得自己拼接sql语句,于是自己封装了一个方法:

public static String beans2db(List<?> objs, String table) {
		
		String sql="";
		StringBuffer prama=new StringBuffer();
		StringBuffer values=new StringBuffer();
		try {
			Field[] fields = (0).getClass().getDeclaredFields();
			for (Field field : fields) {
				(","+());
			}
			for (Object obj : objs) {
				values=(",(").append(getValue2Bean(obj)).append(")");
			}
			
			prama=(0);
			values=(0);
			
		} catch (Exception e) {
			
			();
		}
		
		
		sql="insert into "+table+"("+prama+") values " +values;
		return sql;
	}

参数:objs是bean的list集合,参数table是待插入的数据库表,返回的字符串格式:insert  into TABLE (PRAMA,PRAMA,……) values(VALUE,VALUE,……)  ;

下面是参数值得拼接方法:

    // import 
	
    /**
	 * 参数值拼接
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	private static StringBuffer getValue2Bean(Object obj) throws Exception{
		Field[] fields = ().getDeclaredFields();
		StringBuffer value=new StringBuffer();
		String v= null;
		for (Field field : fields) {
			v=(obj, ());
			if (v==null) {
				(","+(obj, ()));
			}else {
				(",'"+(obj, ())+"'");
			}
		}
		value=(0);
		return value;
	}


方法的结果形式:(VALUE,VALUE,VALUE……),(VALUE,VALUE,VALUE……),(VALUE,VALUE,VALUE……)……