jdbc连接HIVE

  1. 在hive上启动service

     hive --service hiveserver

    wKiom1O7S-jCADlJAAEOpAeTovk287.jpg

  2. 在eclipse中进行开发

    导入需要的jar包(我这个导入的是udf和jdbc连接hive需要的jar包,基本是最简的了)

    wKioL1O7TBqgdcMAAAXp5Qnlzdk218.jpg

 

我的代码,hive的语法就不说了,大家可以修改例子中的sql来进行自己的业务。我的hive没有设置用户名,密码。所以

1
2
3
   Connection con =  new  HiveJDBC().getConnection(
             "jdbc:hive://192.168.192.138:10000/default" "" ""
             );

后两个参数我都是设置的空

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package  com.hive.jdbc;
 
import  java.sql.Connection;
import  java.sql.DriverManager;
import  java.sql.ResultSet;
import  java.sql.SQLException;
import  java.sql.Statement;
 
/**
  * 连接hive
  * @author liqi
  *
  */
public  class  HiveJDBC {
     public  static  final  String driverName =  "org.apache.hadoop.hive.jdbc.HiveDriver" ;
     
     /**
      * 获取连接 
      */
     public  Connection getConnection(String url,String userName,String password){
         try  {
             Class.forName(driverName);
             Connection conn = DriverManager.getConnection(url, userName, password);
             return  conn;
         catch  (ClassNotFoundException e) {
             e.printStackTrace();
         } catch  (SQLException e) {
             e.printStackTrace();
         }
         return  null ;
     }
     
     public  static  void  main(String args[]){
         Connection con =  new  HiveJDBC().getConnection(
             "jdbc:hive://192.168.192.138:10000/default" "" ""
             );
         try  {
             Statement stmt = con.createStatement();
             String sql =  "show tables" ;
             
             ResultSet res = stmt.executeQuery(sql);
             while (res.next()) {
                 sql =  "select * from "  + res.getString( 1 );
                 System.out.println( "tables:"  + res.getString( 1 ));
                 
                 ResultSet resTable = stmt.executeQuery(sql);
                 while (resTable.next()){
                     System.out.println(resTable.getString( 2 ));
                 }
             }
         catch  (SQLException e) {
             e.printStackTrace();
         }
     }
}

 

本文出自 “屌丝程序员的逆袭” 博客,请务必保留此出处http://cdelliqi.blog.51cto.com/9028667/1435695

猜你喜欢

转载自phrmgb.iteye.com/blog/2301184
今日推荐