hive-通过Java API操作

时间:2022-12-26 15:50:54

通过Java API操作hive,算是测试hive第三种对外接口


测试hive 服务启动

hive-通过Java API操作


 package org.admln.hive;

 import java.sql.SQLException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.DriverManager; public class testHive { private static String driverName =
"org.apache.hadoop.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:hive://192.168.126.133:10000/default", "hive", "hadoop");
Statement stmt = con.createStatement();
String tableName = "hellohive";
stmt.execute("drop table if exists " + tableName);
stmt.execute("create table " + tableName +
" (key int, value string)");
System.out.println("Create table success!");
// show tables
String sql = "show tables '" + tableName + "'";
System.out.println("Running: " + sql);
ResultSet res = stmt.executeQuery(sql);
if (res.next()) {
System.out.println(res.getString(1));
} // describe table
sql = "describe " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1) + "\t" + res.getString(2));
} sql = "select * from " + tableName;
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(String.valueOf(res.getInt(1)) + "\t"
+ res.getString(2));
} sql = "select count(1) from " + tableName;
System.out.println("Running: " + sql);
res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(res.getString(1));
}
}
}

结果:

hive-通过Java API操作


jdbc链接中后面两个参数不应该是用户名和密码,我傻乎乎的都天上,但是测试无论填什么或者不填都可以链接成功

为什么会这样,难道hive默认谁都可以链接?


用到的jar包

 hadoop-2.2.0/share/hadoop/common/hadoop-common-2.2.0.jar
$HIVE_HOME/lib/hive-exec-0.11.0.jar
$HIVE_HOME/lib/hive-jdbc-0.11.0.jar
$HIVE_HOME/lib/hive-metastore-0.11.0.jar
$HIVE_HOME/lib/hive-service-0.11.0.jar
$HIVE_HOME/lib/libfb303-0.9.0.jar
$HIVE_HOME/lib/commons-logging-1.0.4.jar
$HIVE_HOME/lib/slf4j-api-1.6.1.jar

代码是摘抄的。

http://www.iteblog.com/archives/846