Java代码实现对Hive的基本操作

概览

1.导入jar包
2.测试

1.导入jar包

确保你的Zookeeper,Hadoop集群和hive启动着

在eclipse上新建java项目,并在项目下建个lib文件夹,然后将jar包放到lib中导入项目
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

hive的lib下的
在这里插入图片描述
将其全部导入到项目中

2.测试

在你要测试的hive的主机的/usr/tmp建个student文件,里面放入一些数据
数据列间使用一个逗号(,)隔开

1
2
3
4
1,lilei
2,hanmeimei
3,xiaoming
4,haha

建个包,建个HiveJDBC测试类

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package com.zy.hivejdbc;

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

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class HiveJDBC {

private static String driverName="org.apache.hive.jdbc.HiveDriver";
private static String url = "jdbc:hive2://192.168.134.153:10000/mydb";
private static String user = "root";
private static String password="root";

private static Connection conn = null;
private static Statement stmt = null;
private static ResultSet rs = null;

@Before
public void init() throws Exception{
Class.forName(driverName);
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
}
@Test
public void createDatabase() throws Exception{
String sql = "create database hive_jdbc_test";
System.out.println("Running: " + sql);
stmt.executeQuery(sql);
}
@Test
public void dropDatabase() throws Exception {
String sql = "drop database if exists hive_jdbc_test";
System.out.println("Running: " + sql);
stmt.execute(sql);
}

@Test
public void showDatabases() throws Exception {
String sql = "show databases";
System.out.println("Running: " + sql + "\n");
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getString(1) );
}
}

@Test
public void createTable() throws Exception {
String sql = "create table t2(id int ,name String) row format delimited fields terminated by ',';";
System.out.println("Running: " + sql);
stmt.execute(sql);
}
@Test
public void loadData() throws Exception {
String filePath = "/usr/tmp/student";
String sql = "load data local inpath '" + filePath + "' overwrite into table t2";
System.out.println("Running: " + sql);
stmt.execute(sql);
}

@Test
public void selectData() throws Exception {
String sql = "select * from t2";
System.out.println("Running: " + sql);
rs = stmt.executeQuery(sql);
System.out.println("编号" + "\t" + "姓名" );
while (rs.next()) {
System.out.println(rs.getInt(1) + "\t" + rs.getString(2));
}
}
@Test
public static void drop(Statement stmt) throws Exception {
String dropSQL = "drop table t2";
boolean bool = stmt.execute(dropSQL);
System.out.println("删除表是否成功:" + bool);
}
@After
public void destory() throws Exception {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
}

}

分别双击方法名右键run Junit test 测试,并在hive和eclipse控制台查看结果