java hivejdbc 工具类
时间: 2023-11-22 12:50:27 浏览: 152
以下是一个Java HiveJDBC工具类的示例,它使用了上述提到的db.properties文件中的配置信息:
```java
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class HiveJdbcUtil {
private static String driverClass;
private static String userName;
private static String password;
private static String url;
static {
try {
// 加载db.properties配置文件
InputStream in = HiveJdbcUtil.class.getClassLoader().getResourceAsStream("db.properties");
Properties props = new Properties();
props.load(in);
// 读取配置信息
driverClass = props.getProperty("driver_class");
userName = props.getProperty("user_name");
password = props.getProperty("password");
url = props.getProperty("url");
// 加载Hive JDBC驱动
Class.forName(driverClass);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取Hive连接
* @return Connection
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 关闭Hive连接
* @param conn Connection
* @param stmt Statement
* @param rs ResultSet
*/
public static void closeConnection(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行Hive SQL查询
* @param sql String
* @return ResultSet
*/
public static ResultSet executeQuery(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeConnection(conn, stmt, null);
}
return rs;
}
}
```
阅读全文