首页 > 代码库 > hive-通过Java API操作

hive-通过Java API操作


通过Java API操作hive,算是测试hive第三种对外接口


 

测试hive 服务启动


 

 1 package org.admln.hive; 2  3 import java.sql.SQLException; 4 import java.sql.Connection; 5 import java.sql.ResultSet; 6 import java.sql.Statement; 7 import java.sql.DriverManager; 8  9 public class testHive {10     11     private static String driverName = 12                    "org.apache.hadoop.hive.jdbc.HiveDriver";13   14     public static void main(String[] args) 15                             throws SQLException {16         try {17             Class.forName(driverName);18         } catch (ClassNotFoundException e) {19             e.printStackTrace();20             System.exit(1);21         }22 23         Connection con = DriverManager.getConnection(24                            "jdbc:hive://192.168.126.133:10000/default", "hive", "hadoop");25         Statement stmt = con.createStatement();26         String tableName = "hellohive";27         stmt.execute("drop table if exists " + tableName);28         stmt.execute("create table " + tableName + 29                                      " (key int, value string)");30         System.out.println("Create table success!");31         // show tables32         String sql = "show tables ‘" + tableName + "‘";33         System.out.println("Running: " + sql);34         ResultSet res = stmt.executeQuery(sql);35         if (res.next()) {36             System.out.println(res.getString(1));37         }38 39         // describe table40         sql = "describe " + tableName;41         System.out.println("Running: " + sql);42         res = stmt.executeQuery(sql);43         while (res.next()) {44             System.out.println(res.getString(1) + "\t" + res.getString(2));45         }46 47 48         sql = "select * from " + tableName;49         res = stmt.executeQuery(sql);50         while (res.next()) {51             System.out.println(String.valueOf(res.getInt(1)) + "\t"52                                                + res.getString(2));53         }54 55         sql = "select count(1) from " + tableName;56         System.out.println("Running: " + sql);57         res = stmt.executeQuery(sql);58         while (res.next()) {59             System.out.println(res.getString(1));60         }61     }62 }

结果:


 

jdbc链接中后面两个参数不应该是用户名和密码,我傻乎乎的都天上,但是测试无论填什么或者不填都可以链接成功

为什么会这样,难道hive默认谁都可以链接?


 

用到的jar包

1 hadoop-2.2.0/share/hadoop/common/hadoop-common-2.2.0.jar2 $HIVE_HOME/lib/hive-exec-0.11.0.jar 3 $HIVE_HOME/lib/hive-jdbc-0.11.0.jar 4 $HIVE_HOME/lib/hive-metastore-0.11.0.jar  5 $HIVE_HOME/lib/hive-service-0.11.0.jar   6 $HIVE_HOME/lib/libfb303-0.9.0.jar   7 $HIVE_HOME/lib/commons-logging-1.0.4.jar  8 $HIVE_HOME/lib/slf4j-api-1.6.1.jar

代码是摘抄的。

http://www.iteblog.com/archives/846


 

hive-通过Java API操作