maven依赖
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.0.0</version>
</dependency>
sql为正常的数据库的查询语句即可
import org.springframework.stereotype.Service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Created by admin on 2019/2/12.
*/
@Service("ConnectHive")
public class ConnectHive {
private static String driverName ="org.apache.hive.jdbc.HiveDriver";
//填写hive的IP,之前在配置文件中配置的IP
private static String Url="jdbc:hive2://主机地址:10000/default";
private static Connection conn;
private static PreparedStatement ps;
private static ResultSet rs;
//创建连接
public static Connection getConnnection(){
try {
Class.forName(driverName);
//此处的用户名一定是有权限操作HDFS的用户
conn = DriverManager.getConnection(Url, "", "");
} catch(ClassNotFoundException e) {
e.printStackTrace();
System.exit(1);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
public static PreparedStatement prepare(Connection conn, String sql) {
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return ps;
}
public static ResultSet queryInformation(String sql){
conn=getConnnection();
rs=searchSql(sql);
return rs;
}
/**
* 执行hive中的sql语句
* @param sql
* @return
*/
public static ResultSet searchSql(String sql) {
System.out.println(sql);
try {
ps=prepare(conn, sql);
rs=ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
注意需要启动一个hive的服务
hive --service hiveserver2 &
检查是否启动用linux命令
netstat -tunlp|grep 10000这个端口要是启动就可以了