使用java(eclipse)遠程連接hive進行數據庫操作(hiveserver2)


hive 版本apache-hive-1.2.1-bin

1.先啟動mysql (sevice mysql start)

2.啟動hive遠程服務,輸入:./hive --service hiveserver2 或者hiveserver2

  如圖服務已經啟動成功;
3.引入jar包到項目中

  jar包 包括:  apache-hive-1.2.1-bin 里面的lib下的jar包,還有hadoop-2.7.1--》share--》hadoop--》common下的hadoop-common-2.7.1.jar

4.在項目中寫入以下代碼即可
   Class.forName("org.apache.hive.jdbc.HiveDriver");
   Connection connection = DriverManager.getConnection("jdbc:hive2://192.168.18.130:10000/", "root","root");

                           URL(該版本端口10000/后可以不加default)      用戶名 密碼
 (端口10000是默認的,也可以在啟動hive遠程服務的時候通過-p設置)   

例:

 

package com.java.hadoop.hive;

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

import org.apache.hadoop.hive.metastore.api.ThriftHiveMetastore.Processor.drop_database;
import org.junit.Before;
import org.junit.Test;

public class TestHive {
	private Connection connection;
	private PreparedStatement ps;
	private ResultSet rs;
	//創建連接
	@Before
	public void getConnection() {
		try {

			Class.forName("org.apache.hive.jdbc.HiveDriver");
			connection = DriverManager.getConnection("jdbc:hive2://192.168.18.130:10000/", "root", "root");
			System.out.println(connection);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//關閉連接
	public void close() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (connection != null) {
				connection.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	// 創建表
	@Test
	public void createTable() {
		String sql = "create table goods2(id int,name string) row format delimited fields terminated by '\t' ";
		try {
			ps = connection.prepareStatement(sql);
			ps.execute(sql);
			close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	// 刪除表
	@Test
	public void dropTable() {
		String sql = "drop table goods";
		try {
			ps = connection.prepareStatement(sql);
			ps.execute();
			close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	//添加數據
	@Test
	public void insert() throws SQLException{
		String sql = "load data inpath '/goods.txt' into table goods";
		//記得先在文件系統中上傳goods.txt
		ps = connection.prepareStatement(sql);
		ps.execute();
		close();
	}
	//查詢
	@Test
	public void find() throws SQLException {
		String sql = "select * from goods ";
		ps = connection.prepareStatement(sql);
		rs = ps.executeQuery();
		while (rs.next()) {
			System.out.println(rs.getObject(1) + "---" + rs.getObject(2));
		}
		close();
	}

	
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM