通用jdbc表插入
作者:互联网
//通用表插入 public static <T> int insertTableList(Connection connection, String tableName, T t){ int flag = -1; QueryRunner queryRunner = new QueryRunner(); Class c=t.getClass(); String sql = "insert into "+tableName+" ("; String sql2 = " values ("; //获取该类的成员变量 Field[] declaredFields = c.getDeclaredFields(); for (Field field : declaredFields) { try {//获取成员变量的类型field.getType().getName() //获取成员变量的名称 sql = sql + field.getName()+","; if (BeanUtils.getProperty(t,field.getName())==null){ sql2 = sql2 + BeanUtils.getProperty(t,field.getName()) +","; } else { sql2 = sql2 + "\"" + BeanUtils.getProperty(t,field.getName()) + "\"" +","; } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } sql = sql.substring(0,sql.length()-1); sql2 = sql2.substring(0,sql2.length()-1); sql = sql+")"+sql2+")"; System.out.println(sql); try { flag = queryRunner.update(connection,sql); } catch (SQLException e) { e.printStackTrace(); } return flag; }
标签:printStackTrace,jdbc,通用,field,sql2,插入,sql,catch,getName 来源: https://www.cnblogs.com/chen-z-w/p/15588937.html