优米格
分享有营养的

Java连接impala示例(jdbc连接impala)

BraUndress.png

目的:提供一个通过 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包地址见[这里]。

参考:

  1. http://www.cloudera.com/documentation/archive/impala/2-x/2-1-x/topics/impala_jdbc.html;
  2. https://cwiki.apache.org/confluence/display/Hive/HiveServer2+Clients;
  3. http://fatkun.com/2013/12/impala-jdbc-example.html;
  4. http://superlxw1234.iteye.com/blog/2008814;
赞(0)
未经允许禁止转载:优米格 » Java连接impala示例(jdbc连接impala)

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系