一、准备好hive的环境,创建表(例如userinfo),添加数据。
create table userinfo(x string, y string);
insert into userinfo values('tju','beiyang');
二、启动hive服务
hive --service hiveserver2
三、项目中添加依赖
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>3.1.2</version>
<exclusions>
<exclusion>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-runner</artifactId>
</exclusion>
</exclusions>
</dependency>
四、读取数据demo:
package cn.edu.tju;
import java.sql.*;
public class HiveJdbcClient {
private static String driverClassName = "org.apache.hive.jdbc.HiveDriver"; //hive的驱动
public static void main(String[] args) throws SQLException {
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
Connection con = DriverManager.getConnection("jdbc:hive2://xxx.xxx.xxx.xxx:10000/default", "", "");
Statement stmt = con.createStatement();
String tableName = "userinfo";
// select
String sql = "select * from " + tableName;
ResultSet res = stmt.executeQuery(sql);
while (res.next()) {
System.out.println(String.valueOf(res.getString(1)) + " " + res.getString(2));
}
}
}