1. 程式人生 > 實用技巧 >Hive通過Jdbc獲取表的欄位資訊

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);
        }
    }