通用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;
    }

 

上一篇:C# DataTable 行转列


下一篇:SQL2 查找入职员工时间排名倒数第三的员工所有信息