Hive通过Jdbc获取表的字段信息

参考代码如下:

 /**
     * 按顺序返回字段
     * desc table的返回结果形式如下:
     hive> describe ind01acoM;
     OK
     acq_ins_id_cd           string
     cups_sig_card_in        string
     resv                    string
     ins_id_cd               string
     hp_settle_dt            string

     # Partition Information
     # col_name              data_type               comment

     ins_id_cd               string
     hp_settle_dt            string
     */
    public Map<String, String> queryAllColumnsAndType(String table) throws Exception {
        //Map<String, String> allColumnsAndType = new CaseInsensitiveMap();
        //为了保证字段顺序
        Map<String, String> allColumnsAndType = new LinkedHashMap<>();
        Connection connection = null;
        try{
            connection = getConnection();
            ResultSet rs = connection.createStatement().executeQuery("describe " + table);
            if (rs != null) {
                while (rs.next()) {
                    String col_name = rs.getString("col_name");
                    if(!StringUtils.isBlank(col_name)){
                        allColumnsAndType.put(rs.getObject("col_name").toString(), rs.getObject("data_type").toString());
                    }else break;
                    //System.out.println(rs.getString("col_name") + "\t" + rs.getString("data_type"));
                }
            }
            //去除分区列
            allColumnsAndType.remove("hp_settle_dt");
            allColumnsAndType.remove("ins_id_cd");
            return allColumnsAndType;
        }catch(Exception e){
            e.printStackTrace();
            logger.error("获取字段-类型失败,表:{}",table);
            throw e;
        }finally {
            closeConn(null, null, connection);
        }
    }

posted @ 2020-10-13 17:23  远去的列车  阅读(2874)  评论(0编辑  收藏  举报