操作hive的方法前面只介紹了hive客戶端方式,但是被官方定義為過時(shí)(雖然還是最常用的),其他操作hive的方式有beeline、webUI、JavaAPI(官方最推薦的方式是beeline)。這幾種客戶端方式需要服務(wù)hiveserver2的支持,所以首先我們需要先啟動(dòng)該服務(wù)。
1、hiveserver2啟動(dòng)
默認(rèn)啟動(dòng)方式,默認(rèn)端口10000
$ ./hiveserver2
$ hive --service hiveserver2
修改啟動(dòng)端口
./hiveserver2 --hiveconf hive.server2.thrift.port=14000
2、beeline連接
第一種連接方式,模式如下:
$ bin/beeline
beeline> !connect jdbc:hive2://localhost:10000 username password
默認(rèn)是沒有密碼的,默認(rèn)用戶是hdfs默認(rèn)的超級(jí)用戶hadoop,hive-site.xml可以設(shè)置具體的驗(yàn)證方式和相應(yīng)參數(shù)
$ ./beeline
beeline>!connect jdbc:hive2://localhost:10000 hadoop
登錄成功后即可按照正常的HQL操作hive了
3、JavaAPI
添加依賴
groupId:org.apache.hive
artifactId:hive-jdbc
version:對(duì)應(yīng)hive版本
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager;
public class HiveJdbcClient {
private static String driverName ="org.apache.hive.jdbc.HiveDriver";
public static void main(String[]args)throws SQLException {
try {
Class.forName(driverName);
}catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con =DriverManager.getConnection("jdbc:hive2://192.168.205.131:10000/test","hadoop","");
Statement stmt =con.createStatement();
String tableName ="a";
ResultSet res =stmt.executeQuery("select * from? " +tableName);
while (res.next()) {
System.out.println(res.getString(1) +"\t" +res.getString(2));
}
}
}
注意:從官方網(wǎng)站復(fù)制代碼需要注意兩點(diǎn),默認(rèn)的是hive1的連接方式,不是hiveserver2的,需要修改驅(qū)動(dòng)和URL
4、WebUI的方式
推薦使用HUE,不推薦使用hive自帶的UI