Hive 의 JDBC 인터페이스

3945 단어 Hive
더 읽 기
>>>eclipse 에서 JDBC 를 사용 하여 Hive 에 연결 하기 전에 Hive 감청 사용자 링크 를 열 어야 합 니 다.
hive/bin/ext$ hive --service hiveserver
>>>eclipse 환경 설정
pom.xml 에 hive 패키지 의존 추가

    UTF-8
    2.5.0
    0.13.1
 

 
  	
  	 	org.apache.hadoop
  	 	hadoop-client
  	 	${hadoop.version}
 


  		org.apache.hive
  		hive-jdbc
  		${hive.version}
 
  	
  
  		org.apache.hive
  		hive-exec
  		${hive.version}
  

 >>>예제 코드:
package com.fb.hadoop.hive;

import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
 
public class HiveJdbcClient {
  private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
 
  public static void main(String[] args) throws SQLException {
   //  JDBC
    try {
      Class.forName(driverName);
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.exit(1);
    }
    //    
    Connection con = DriverManager.getConnection("jdbc:hive://master:10000/default", "root", "gsdjsj");
    Statement stmt = con.createStatement();
    String tableName = "user2";
    stmt.executeQuery("drop table " + tableName);
    ResultSet res = stmt.executeQuery("create table " + tableName + " (name string,age int,sex string,phone string)"
    		+"ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'"
    		+"STORED AS TEXTFILE");
    // show tables
    String sql = "show tables '" + tableName + "'";
    System.out.println("Running: " + sql);
    res = stmt.executeQuery(sql);
    if (res.next()) {
      System.out.println(res.getString(1));
    }
    // describe table
    sql = "describe " + tableName;
    System.out.println("Running: " + sql);
    res = stmt.executeQuery(sql);
    while (res.next()) {
      System.out.println(res.getString(1) + "\t" + res.getString(2));
    }
 
    // load data into table
    // NOTE: filepath has to be local to the hive server
    // NOTE: /tmp/a.txt is a ctrl-A separated file with two fields per line
    String filepath = "/opt/data/user.txt";
    sql = "load data local inpath '" + filepath + "' into table " + tableName;
    System.out.println("Running: " + sql);
    res = stmt.executeQuery(sql);
 
    // select * query
    sql = "select * from " + tableName;
    System.out.println("Running: " + sql);
    res = stmt.executeQuery(sql);
    while (res.next()) {
      System.out.println(String.valueOf(res.getString(1)) + "\t" + res.getInt(2));
    }
 
    // regular hive query
    sql = "select count(1) from " + tableName;
    System.out.println("Running: " + sql);
    res = stmt.executeQuery(sql);
    while (res.next()) {
      System.out.println(res.getString(1));
    }
  }
}

 

좋은 웹페이지 즐겨찾기