Java调用Hive的操作

     如何在Java中调用Hive的操作步骤如下:

1、启动Hive远程服务:

      命令: hive --service hiveserver2  &

      启动成功,命令框出现以下界面:

     

2、在Eclipse中创建Hadoop 项目,导入Hive的必须包

  Hive的必须包如下:

   hive-exec-2.0.0.jar

   hive-jdbc-2.0.0.jar

   hive-service-2.0.0.jar

   httpclient-4.4.jar

   httpcore-4.4.jar

3、编写Java调用Hive的相关函数,代码如下:

package com;

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

public class HiveTestCase {
public static void query(Statement stmt) throws Exception {
String querySQL = "select a.* from java_test a";
ResultSet res = stmt.executeQuery(querySQL); // 执行查询语句
while (res.next()) {
System.out.print("id:" + res.getString("id") + " ");
System.out.println("name:" + res.getString(2) + " ");
}
}

public static void create(Statement stmt) throws Exception {
String createSQL = "create table java_test (id string, name string) row format delimited fields terminated by '\t' ";
boolean bool = stmt.execute(createSQL);
System.out.println("创建表是否成功:" + bool);
}


public static void drop(Statement stmt) throws Exception {
String dropSQL = "drop table java_test";
boolean bool = stmt.execute(dropSQL);
System.out.println("删除表是否成功:" + bool);
}

public static void load(Statement stmt) throws Exception {
String loadSQL = "load data local inpath '/home/hadoop/test' into table java_test ";
boolean bool = stmt.execute(loadSQL);
System.out.println("导入数据是否成功:" + bool);
}

public static void main(String[] args) throws Exception {

Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.26.131:10000/test", "", "");
Statement stmt = con.createStatement();

drop(stmt); // 执行删除语句
create(stmt); // 执行建表语句
load(stmt); // 执行导入语句
query(stmt); // 执行查询语句
}
}

4、如果出现错误:User: hadoop is not allowed to impersonate 

解决:在hive-site.xml文件中添加一下配置:

   

      hive.metastore.sasl.enabled

      false

      If true, the metastore Thrift interface will be secured with SASL.  

                   Clients must authenticate with Kerberos.

   

   

       hive.server2.enable.doAs

       false

   

   

       hive.server2.authentication

       NONE

   

   参考链接:

   http://stackoverflow.com/questions/36909002/authorizationexception-user-not-allowed-to-impersonate-user

5、操作过程存在的疑问:

执行以上HQL语句,都能在Hive中成功执行创建表、删除表、导入数据等,但是函数返回的布尔值为什么为 false 呢?

解答:

这个execute方法执行一个sql语句并且指向第一个返回值。
返回值:true表示第一个返回值是一个ResultSet对象;false表示这是一个更新个数或者没有结果集。   

你可能感兴趣的:(Hive,Java,api,HQL)