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

时间:2024-03-15 07:34:49

1.导入jar包

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

在eclipse上新建java项目,并在项目下建个lib文件夹,然后将jar包放到lib中导入项目
Java代码实现对hive的基本操作
Java代码实现对hive的基本操作
Java代码实现对hive的基本操作

hive的lib下的
Java代码实现对hive的基本操作
将其全部导入到项目中

2.测试

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

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

建个包,建个HiveJDBC测试类

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控制台查看结果