Java API操作Hive

官网地址
https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients#HiveServer2Clients-JDBC

一、启动hiveserver2
使用Java API操作hive之前必须启动hiveserver2(服务都没起,客户端怎么可能访问的到呢?)

启动命令

[root@hadoop001 bin]# hiveserver2 &
[1] 7495
[root@hadoop001 bin]# which: no hbase in (/bin:/opt/app/sqoop-1.4.6-cdh5.7.0/bin:/opt/app/hive-1.1.0-cdh5.7.0/bin:/bin:/opt/app/2.6.0-cdh5.7.0/bin:/opt/app/2.6.0-cdh5.7.0/sbin:/bin:/opt/software/findbugs-1.3.9/bin:/usr/local/protobuf/bin:/opt/software/maven-3.3.9/bin:/usr/java/jdk1.8/bin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin)

客户端操作hive的结果会在这个界面打印出来(操作成功会显示ok,失败会有失败的一些信息)

二、IDEA构建Java API

package com.ruozedata.hive;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class HiveJDBC {
    public static  String driveName="org.apache.hive.jdbc.HiveDriver";
    public static  String url="jdbc:hive2://192.168.187.111:10000/default";
    public static  String username="root";
    public static  String password="";

    public static void main(String[] args) throws Exception {
        Class.forName(driveName);
        Connection con=DriverManager.getConnection(url,username,password);
         Statement stms=con.createStatement();
        String tableName = "testHiveDriverTable";
        stms.execute("drop table if exists " + tableName);
        stms.execute("create table " + tableName + " (key int, value string)");
        // show tables
        String sql = "show tables '" + tableName + "'";
        System.out.println("Running: " + sql);
        ResultSet res = stms.executeQuery(sql);
        if (res.next()) {
            System.out.println(res.getString(1));
        }

    }
}

以上API是在Hive当中创建一张testHiveDriverTable表,至于删除表之类,大家可以参考官网。

三、验证
可以看到testhivedrivertable表已创建成功

hive (default)> show tables;
OK
tab_name
emp
emp_external
testhivedrivertable
Time taken: 0.989 seconds, Fetched: 3 row(s)

server端会给出最后操作的结果(OK)

[root@hadoop001 bin]# hiveserver2 &
[1] 7495
[root@hadoop001 bin]# which: no hbase in (/bin:/opt/app/sqoop-1.4.6-cdh5.7.0/bin:/opt/app/hive-1.1.0-cdh5.7.0/bin:/bin:/opt/app/2.6.0-cdh5.7.0/bin:/opt/app/2.6.0-cdh5.7.0/sbin:/bin:/opt/software/findbugs-1.3.9/bin:/usr/local/protobuf/bin:/opt/software/maven-3.3.9/bin:/usr/java/jdk1.8/bin:/usr/lib64/qt-3.3/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin)
OK
OK
OK

你可能感兴趣的:(Hive)