使用前引入必要的mvn依赖:
<dependency>
<groupId>org.apache.hive</groupId>
<artifactId>hive-jdbc</artifactId>
<version>2.3.3</version>
</dependency>
下面是整合代码:
public class ImpalaUtil {
private static final org.apache.log4j.Logger logger= LogManager.getLogger(ImpalaUtil.class);
/**
* 获取连接实例
* @param jdbcUrl
* @param jdbcDriver
* @return
* @throws Exception
*/
public static Connection getInstance(String jdbcUrl,String jdbcDriver) throws Exception{
//加载驱动
Class.forName(jdbcDriver);
//创建连接
return DriverManager.getConnection(jdbcUrl);
}
/**
* 构建查询工具类模板
* @param jdbcUrl
* @param jdbcDriver
* @param sql
* @throws SQLException
*/
public static <R> R executeSql(String jdbcUrl, String jdbcDriver, String sql, Function<ResultSet,R> function) throws SQLException {
Connection con = null;
Statement stmt = null;
ResultSet resultSet = null;
try {
con = getInstance(jdbcUrl, jdbcDriver);
//创建语句
stmt = con.createStatement();
//执行sql并返回结果
resultSet = stmt.executeQuery(sql);
//处理返回结果
return function.apply(resultSet);
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
releaseResource(con,stmt,null,resultSet);
}
return null;
}
/**
* 关闭连接,释放资源
* @param conn
* @param statement
* @param preparedStatement
* @param rs
*/
public static void releaseResource(Connection conn, Statement statement, PreparedStatement preparedStatement, ResultSet rs) {
try {
if (rs != null) {
try {
rs.close();
} catch (Throwable e) {
e.printStackTrace();
logger.error(e);
logger.error("关闭rs失败");
}
}
if (statement != null) {
try {
statement.close();
} catch (Throwable e) {
e.printStackTrace();
logger.error(e);
logger.error("关闭statement失败");
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (Throwable e) {
e.printStackTrace();
logger.error(e);
logger.error("关闭preparedStatement失败");
}
}
if (conn != null) {
try {
conn.close();
} catch (Throwable e) {
e.printStackTrace();
logger.error(e);
logger.error("关闭conn失败");
}
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
网友评论