首页 > 其他分享 >impala jdbc导出hive数据字典

impala jdbc导出hive数据字典

时间:2023-05-17 10:00:33浏览次数:43  
标签:jdbc String getString rs System hive println new impala

业务需求太多了,给完整导出为html文件,以及之前搞的

public static void main(String[] args) throws Exception {
        kerberos();

    }

    public static void kerberos() {
        URL resource = Thread.currentThread().getContextClassLoader().getResource("");
        String basePath = resource.getPath();
        System.setProperty("java.security.krb5.conf", basePath + "kerberos/krb5.conf");
        UserGroupInformation.setConfiguration(HadoopKbsConfiguration.getHadoopKbsConfiguration());

        try {
            UserGroupInformation.loginUserFromKeytab("bigdata", basePath + "kerberos/bigdata.keytab");
            UserGroupInformation logUser = UserGroupInformation.getLoginUser();
            System.out.println("登录成功");
            if (null == logUser) {
                throw new BaseException("login user can not be empty!");
            }
            logUser.doAs(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    System.out.println("start");
//                    impala sql
//                    dmlSqlFindByTableName();
//                    dmlAutoFindByDatabase();// 导出一个库下所有的建表语句
//                    getDml2Excel();
                    getDataBaseDict();
                    System.out.println("end");
                    return null;
                }
            });

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void dmlAutoFindByMysql() {

    }

    //把单个的建表语句的字段搞成excel格式,目的提供数据字典
    public static void getDml2Excel() {
        String connectionUrl1 = "jdbc:impala://IP:25004/ic_cdm;AuthMech=1;KrbHostFQDN=master03-cdp;KrbServiceName=impala;OptimizedInsert=0;UseNativeQuery=1;";
        String jdbcDriverName1 = "com.cloudera.impala.jdbc41.Driver";
        //加载驱动
        try {
            Class.forName(jdbcDriverName1);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try (Connection con = DriverManager.getConnection(connectionUrl1)) {
            DatabaseMetaData md = con.getMetaData();
            ResultSet columns = md.getColumns(null, "ic_cdm", "t_dim_model_price_map_h", "%");
            String table_name = columns.getString("TABLE_NAME");
            String table_remark = columns.getString("REMARKS");
            List<List<String>> rows = new ArrayList<>();
			// hutools 工具
            ExcelWriter writer = ExcelUtil.getWriter("D:/writeTest.xlsx");
            while (columns.next()) {
                String column_name = columns.getString("COLUMN_NAME");
                String remark = columns.getString("REMARKS");
                String type = columns.getString("TYPE_NAME");
                System.out.println(column_name + "  " + remark + " " + type);
                List<String> row = CollUtil.newArrayList(column_name, remark, type);
                rows.add(row);
            }
            writer.merge(rows.size() - 1, "测试标题");
            writer.write(rows);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    public static void getDataBaseDict() {
        FileSystemView fsv = FileSystemView.getFileSystemView();
        String path = fsv.getHomeDirectory().toString();//获取当前用户桌面路径
        String connectionUrl1 = "jdbc:impala://IP:25004/ic_cdm;AuthMech=1;KrbHostFQDN=IP;KrbServiceName=impala;OptimizedInsert=0;UseNativeQuery=1;";
        String jdbcDriverName1 = "com.cloudera.impala.jdbc41.Driver";
        //加载驱动
        try {
            Class.forName(jdbcDriverName1);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            Connection con = DriverManager.getConnection(connectionUrl1);
            DatabaseMetaData dbmd = con.getMetaData();
            ResultSet resultSet = dbmd.getTables(null, "ic_cdm", "%", new String[]{"TABLE"});
            File directory = new File(path);
            FileWriter fw = new FileWriter(directory + "\\数据字典.html");
            fw.write("<html>");

            while (resultSet.next()) {
                String tableName = resultSet.getString("TABLE_NAME");
                String tableRemark = resultSet.getString("REMARKS");
                System.out.println(tableRemark);

                if (tableName.contains("_k") || tableName.contains("_bak") || tableName.contains("dim")
                        || tableName.contains("dwd")) {
                    continue;
                }

                ResultSet rs = dbmd.getColumns(null, "%", tableName, "%");

                fw.write("<table  border=\"10\" cellspacing=\"0\" align=\"center\" cellpadding=\"30\"  >"
                        + "<caption>" +tableRemark +": "+tableName + "</caption>\n"
                        + "<tr><th>列名</th><th>注释</th><th>类型</th></tr>");
                while (rs.next()) {
                    fw.write("<tr>");
                    String column_name = rs.getString("COLUMN_NAME");
                    String remark = rs.getString("REMARKS");
                    String type = rs.getString("TYPE_NAME");
                    System.out.println(column_name + "," + remark + "," + type);
//                    System.out.println("字段名:" + rs.getString("COLUMN_NAME") + "\t字段注释:" + rs.getString("REMARKS") + "\t字段数据类型:" + rs.getString("TYPE_NAME"));
                    fw.write("<td>" + column_name + "</td>" + "<td>" + remark + "</td>" + "<td>" + type + "</td>");
                    fw.write("</tr>");
                }
                fw.write("</table>");
                fw.write("<hr></hr>");
            }
            fw.write("</html>");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void outDict2Word() {

    }

    public static void outDict2Excel() {

    }

    public static void outDict2Html() {

    }


    public static void dmlAutoFindByDatabase() {

        String connectionUrl = "jdbc:impala://ip:25004/ic_ods;AuthMech=1;KrbHostFQDN=ip;KrbServiceName=impala;OptimizedInsert=0;UseNativeQuery=1;";
        String jdbcDriverName = "com.cloudera.impala.jdbc41.Driver";
        //简单的一个查询语句

        String sqlStatement = "use ic_ods;";
        String showTablesStatement = "show tables;";
        String showDmlTableStatement = "show create table ";
        String tableNames = "t_ods_api_ds_k";

        //加载驱动
        try {
            Class.forName(jdbcDriverName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try (Connection con = DriverManager.getConnection(connectionUrl)) {
            Statement stmt = con.createStatement();
            System.out.println("---begin query---");
            boolean execute = stmt.execute(sqlStatement);
            if (!execute) {
                ResultSet rs = stmt.executeQuery(showTablesStatement);
                while (rs.next()) {
                    String curName = rs.getString(1);
                    if (!curName.contains("bak") && !curName.contains("_k") && !curName.contains("_test") && !curName.contains("_tmp")) {
                        tableNames = tableNames + "," + rs.getString(1);
                        System.out.println(rs.getString(1));
                    }


                }
            }
            String[] tables = tableNames.split(",");
            //查询
            Map<String, String> map = new HashMap<String, String>();
            for (String table : tables) {
                if (table == null || table == "" || table == " ") {
                    continue;
                }
                String sql = showDmlTableStatement + table + ";";
                String curSql = "";
//                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                //打印输出
                while (rs.next()) {
                    curSql = curSql + rs.getString(1) + "\r\n\r\n";
                    System.out.println(rs.getString(1));
                }
                map.put(table, curSql);
            }

            System.out.println("---end query---");
            URL resource = Thread.currentThread().getContextClassLoader().getResource("");
            String basePath = resource.getPath();
            File file = new File("D:\\建表语句.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            for (Map.Entry<String, String> entity : map.entrySet()) {
                String tName = entity.getKey();
                String sqlTable = map.get(tName);
                fw.write(sqlTable);
            }
            fw.close();
            System.out.println("succ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void dmlSqlFindByTableName() {

        String connectionUrl = "jdbc:impala://IP:25004/ic_cdm;AuthMech=1;KrbHostFQDN=ip;KrbServiceName=impala;OptimizedInsert=0;UseNativeQuery=1;";
        String jdbcDriverName = "com.cloudera.impala.jdbc41.Driver";
        //简单的一个查询语句
        String[] tables = "".split(",");

        String sqlStatement = "show create table ic_cdm.t_quantity_ds_h;";

        //加载驱动
        try {
            Class.forName(jdbcDriverName);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }

        try (Connection con = DriverManager.getConnection(connectionUrl)) {
            //查询
            Map<String, String> map = new HashMap<String, String>();
            for (String table : tables) {
                String sql = "show create table " + table + ";";
                String curSql = "";
                Statement stmt = con.createStatement();
                ResultSet rs = stmt.executeQuery(sql);
                System.out.println("---begin query---");

                //打印输出
                while (rs.next()) {
                    curSql = curSql + rs.getString(1);
                    System.out.println(rs.getString(1));
                }
                map.put(table, curSql);
            }

            System.out.println("---end query---");
            URL resource = Thread.currentThread().getContextClassLoader().getResource("");
            String basePath = resource.getPath();
            File file = new File("D:\\建表语句.txt");
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file);
            for (Map.Entry<String, String> entity : map.entrySet()) {
                String tName = entity.getKey();
                String sqlTable = map.get(tName);
                fw.write(sqlTable);
            }
            fw.close();
            System.out.println("succ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

标签:jdbc,String,getString,rs,System,hive,println,new,impala
From: https://www.cnblogs.com/hbym/p/17407644.html

相关文章

  • 【遇到的问题】com.mysql.jdbc.MysqlDataTruncation 报错
    com.mysql.jdbc.MysqlDataTruncation:Datatruncation:Incorrectdatevalue:‘null’forcolum‘time’atrow1发现代码执行过程中数据存储失败,但是在数据库中执行语句又可以成功。在网络上搜索解决方案,但都解决无果:以为是String类型和Date类型转换的问题mysql-......
  • 1、通过亿级数据量在hive和impala中查询比较text、orc和parquet性能表现(二)
    文章目录9、分别在hive和impala中查询验证结果(比較HDFS存儲三種格式文件的查詢性能textfile、orc、parquet)1)、查詢總條數2)、隨便找一條信息,按照name查詢3)、按照多条件查询4)、按照時間區間查詢5)、兩張表join6)、總結1、文件存儲2、hive查詢與impala查詢速度3、不同查詢類型的查詢......
  • JDBC学习日志五,JDBC操作事务
    事务:要么成功,要么失败ACID原则原子性:要么全部完成,要么都不完成一致性:最终的结果总数据不发生改变隔离性:多个进程互不干扰持久性:数据一旦提交不可逆,持久化到数据库模拟转账事务//模拟转账publicclassTransferDemo{publicstaticvoidmain(String[]args)th......
  • maven引入ojdbc14.jar的方法
    1、ojdbc14.jar的导入方法:①与导入其它jar包相同,在项目pom.xml文件中,可以采用Dependencies向导搜索并导入代码,可以发现其GroupId为com.oracle,ArtifactId为ojdbc14,目前最新版本为:10.2.0.4.0,因此有如下代码:com.oracleojdbc1410.2.0.4.0如果是其它一些常见的包,如Struts、Sprin......
  • JDBC学习日志四,PreparedStatement
    PreparedStatement可以防止sql注入问题,效率更高先进行预编译sql,将要设置的字段值使用占位符本质:预编译会将传递进来的参数包裹成字符,而单引号会被转义字符转换为空内容,有效的防止sql注入的问题CRUD--SELECTStringsql="select*fromuserswhereid=?";st=......
  • Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class
    报错代码Loadingclass`com.mysql.jdbc.Driver'.Thisisdeprecated.Thenewdriverclassis`com.mysql.cj.jdbc.Driver'.ThedriverisautomaticallyregisteredviatheSPIandmanualloadingofthedriverclassisgenerallyunnecessary.Exceptionin......
  • JDBC学习日志二,第一个JDBC程序与JDBC对象解释
    第一步,创建user表,测试数据库CREATEDATABASE`jdbcstudy`/*!40100DEFAULTCHARACTERSETutf8mb3*//*!80016DEFAULTENCRYPTION='N'*/usejdbcstudy;CREATETABLE`users`(`id`intNOTNULL,`NAME`varchar(40)DEFAULTNULL,`PASSWORD`varchar(40......
  • 小知识:设置archive_lag_target参数强制日志切换
    为客户测试一个ADG场景问题,发现测试环境的日志切换频率过低,总是需要定期手工切换,这非常影响测试心情。实际上,可以设置archive_lag_target参数强制日志切换。比如设置:altersystemsetarchive_lag_target=1800;这样即使库没任何压力,半小时也会切换一次日志。该设置同时也适......
  • Spring层引入数据库jdbc需要导的包
    <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.21</version></dependency><dependency>......
  • JDBC 数据库连接池之Driud
    1数据库连接池简介数据库连接池是个容器,负责分配、管理数据库连接(Connection)它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏好处资源重用提升系统响应速度避免......