java JDBC 鏈接hive 操作實例

1.在eclipse下面 導入包,簡便方式 new ->mapred project -> 右鍵 ->選擇“Properties”->Java Build Path->Library->Add External Jars 將/usr/hive/lib的所有jar包 添加上。(因爲之前的配置 所有jar包 已經包括 java鏈接mysql的包)。

2. 開啓服務接口:

hive --service hiveserver >/dev/null 2>/dev/null & 

        或者:hive --service hiveservice

3. 編寫測試代碼:

package hive;

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

public class hiveTest {
	/**
	 * @XD
	 */
	private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver";
	private static String sql = "";
	private static ResultSet res;
	public static void main(String[] args) throws SQLException {
		// TODO Auto-generated method stub
		try{
			Class.forName(driverName);
		}catch(ClassNotFoundException  e){
			e.printStackTrace();
			System.exit(1);
		}
		Connection conn = DriverManager.getConnection("jdbc:hive://localhost:10000/default", "", "");
		Statement stmt = conn.createStatement();
		//創建的表名
		String tablename = "test";
		
		//stmt.executeQuery(sql)和res = stmt.executeQuery(sql); 成對出現 一面出錯
		/**
		 * Tips :sql語句的 注意事項  和hive shell 裏面的一致 
		 * 	sql = " drop table " 注意空格的要求 不能緊挨着書寫 會出現錯誤
		 * 
		 * */
		sql = " drop table "+tablename;
		stmt.executeQuery(sql);
		res = stmt.executeQuery(sql);
		
		sql = " create table "+tablename+"(key int,value string)";
		sql += "row format delimited fields terminated by '\t'";
		res = stmt.executeQuery(sql);
		
		/**
		 * test.txt:(分隔符\t)
		 * 1			xd
		 * 2			xd
		 * 3			xd
		 * 
		 * */
		String filepath = "/home/hadoop/桌面/test.txt";
		sql = " load data local inpath '"+filepath+"' overwrite into table "+tablename;
		stmt.executeQuery(sql);
		res = stmt.executeQuery(sql);
		
		sql = "select * from "+tablename ;
		res = stmt.executeQuery(sql);
		while(res.next()){
			System.out.println(res.getInt(1)+"\t"+res.getString(2));
		}
		
		sql = "select * from userinfo" ;
		res = stmt.executeQuery(sql);
		while(res.next()){
			System.out.println(res.getString(1));
		}
		
		//雖然hive創建視圖的時候 在hive數據倉庫目裏顯示不出來 但是api鏈接的是hive數據庫 可以將視圖顯示出來
		sql = "show tables";
		res = stmt.executeQuery(sql);
		while(res.next()){
			System.out.println(res.getString(1));
		}
	}
}
結果如下:

1	xd
2	xd
3	xd

1
2
3

btest
choice
classino
name_classnum //視圖名
ptest
t1
test
userinfo



發佈了102 篇原創文章 · 獲贊 16 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章