目的:提供一个通过 Java代码连接impala,进行查询操作的方法。
实现代码如下:
1.获取连接的工厂方法ImpalaFactory.java
public class ImpalaFactory {
private static ThreadLocal<Connection> connections = new ThreadLocal<Connection>();
private static ResourceBundle rb = ResourceBundle.getBundle("jdbc");
private static String url = rb.getString("impala.url");
private static String driver = rb.getString("impala.drive");
/**
* 创建连接
* @return
* @throws SQLException
*/
private static Connection getConn() throws SQLException {
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
// 记日志
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
throw e;
}
return conn;
}
/**
* 获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
Connection conn = connections.get();
if (conn == null) {
conn = getConn();
connections.set(conn);
}
return conn;
}
}
2.进行查询操作的示例代码ImpalaTest.java
public class ImpalaTest {
private static final String SQL_STATEMENT = "select count(*) from tb_e2e_bandwidth_crm_order";
public static void main(String[] args) {
System.out.println("\n=============================================");
System.out.println("Cloudera Impala JDBC Example");
System.out.println("Running Query: " + SQL_STATEMENT);
Connection con = null;
try {
con = ImpalaFactory.getConnection();
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(SQL_STATEMENT);
System.out.println("\n== Begin Query Results ======================");
// print the results to the console
while (rs.next()) {
// the example query returns one String column
System.out.println(rs.getString(1));
}
System.out.println("== End Query Results =======================\n\n");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (Exception e) {
// swallow
}
}
}
}
示例中涉及到的jar包详情参考[这里],下载jar包地址见[这里]。
参考:
- http://www.cloudera.com/documentation/archive/impala/2-x/2-1-x/topics/impala_jdbc.html;
- https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients;
- http://fatkun.com/2013/12/impala-jdbc-example.html;
- http://superlxw1234.iteye.com/blog/2008814;
最新评论
我的是ipv4网络,如何使用直播源啊!
我今天试了,不想啊,我的是新疆昌吉移动的网络。
收不到验证码电报
现在充值29起了