jdbc连接hive数据库
hive驱动依赖添加
<!-- hive-jdbc -->
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.1.1</version>
</dependency>
这里需要注意版本,可能有些版本不一定可以连接成功。
逻辑实现层业务代码:
private static String driverName = "org.apache.hive.jdbc.HiveDriver";
private static String url = "jdbc:hive2://xxx.xx.xx.xxx:10000";
public static final String user = "root";
public static final String password = "";
动态拼接sql进行解析展示数据
public List<Object> hiveSelfConnection(String tableName, String baseName) throws Exception {
List<Object> list = new ArrayList<>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
String sql = " select * from " + baseName + '.' + tableName + " limit 0,20 ";
try {
Class.forName(driverName);
conn = DriverManager.getConnection(url, user, password);
if (conn == null) return null;
st = conn.createStatement();
rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while (rs.next()) {
Map<String, Object> sqlMap = new HashMap<>();
for (int i = 0; i < columnCount; i++) {
String key = metaData.getColumnLabel(i + 1);
Object value = rs.getObject(key);
sqlMap.put(key, value);
}
list.add(sqlMap);
}
return list;
} catch (ClassNotFoundException e) {
throw new CustomException("There is a problem in obtaining information about hive database through JDBC :" + e.getMessage());
} finally {
closeAll(conn, st, rs);
}
}
postman测试验证: 这里有个点就是,前端传入的库名表名是动态的,我们不可能提前知道表里面的字段信息以及相关的表结构,这个我们借助
rs.getMetaData() 获得表结构
进行相关的业务逻辑处理得到需要的信息。
举例如下: 1、得到查询结果,一个数据集
resultSet2 = stat.executeQuery("select * from "
+ table_name + " limit " + pageNum + ",100");
2、得到结果集(rs)的结构信息,比如字段数、字段名等
ResultSetMetaData es=rs.getMetaData();
3、使用rs.getMetaData().getTableName(1))就可以返回表名 4、rs.getMetaData().getColumnCount()字段数 5、rs.getMetaData().getColumnName(i));字段名
附连接池关闭以及mysql连接方法:
package com.gotion.dataextract.utils;
import java.sql.*;
public class JdbcUtil {
public static Connection getConnection(String url, String username, String password) {
Connection connection;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return connection;
}
public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|