1.添加包依赖
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-common</artifactId>
<version>2.7.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc -->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>1.2.1</version>
</dependency>
2.启动hiveserver2
hiveserver2
3.查看RunJar端口
netstat -tnlp | grep (RunJarPID)
4.编写代码
import java.sql.*;
public class HiveJDBC {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection conn = DriverManager.getConnection("jdbc:hive2://master:10000/test1");
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("select * from students limit 10");
while (rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
System.out.println(id+","+name);
}
rs.close();
stat.close();
conn.close();
}
}
5.运行结果
注意
复杂sql(启动mapreduce任务的)需要加上用户,否者会报错。
Connection conn = DriverManager.getConnection("jdbc:hive2://master:10000/test1","root","");