使用Phoenix的JDBC接口

来源:互联网 发布:网络摄像头直播软件 编辑:程序博客网 时间:2024/05/16 00:57

使用Phoenix的JDBC接口

Phoenix提供了JDBC接口,可以在Client中方便地以SQL的形式来访问HBase中的数据。

下面以Java代码来展示用法


/** * Created by tao on 4/20/15. * * 运行方法: *  java -cp rest-server-1.0-SNAPSHOT.jar:jars/* cn.gridx.examples.TestPhoenix * * 其中,目录jars中的文件为:avro-1.7.7.jar, bigdata-1.0-SNAPSHOT.jar, phoenix-4.3.1-client.jar * * 通过JDBC接口访问Phoenix时,不需要包含hbase-site.xml、core-site.xml等配置文件,也不需要在classpath中包含hadoop有关的jar包 * * 如果出现类似于如下的异常: *      Exception in thread "main" java.lang.RuntimeException: hbase-default.xml file seems to be for and old version of HBase (0.98.9-hadoop2), this version is 0.98.6-cdh5.2.0 * * 说明classpath有问题 */public class TestPhoenix {    public static void main(String[] args) throws SQLException {        Statement stmt = null;        ResultSet rs = null;        String viewName = "\"food:products\""; // 这是对HBase表"food:products"创建的Phoenix view        System.err.println("\n[viewName = " + viewName + "]\n" );        /* ecs1.njzd.com:2181是zookeeper的某一个节点的ip:port            即使集群中的ZooKeeper存在多个节点,这里也只需要写出一个节点的ip:port就可以了*/           // 如果是Scala,还需要这一句          //Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");        Connection conn = DriverManager.getConnection("jdbc:phoenix:ecs1.njzd.com:2181");        /* 在Phoenix中,如果table name/view name、column name等字符串不加上双引号就会被认为是大写。所以,这里的brand_name要加上双引号  */        PreparedStatement pstmt = conn.prepareStatement("select * from " + viewName + " where \"brand_name\" like '%雀巢%' limit 1");        rs = pstmt.executeQuery();        StringBuffer sb = new StringBuffer();        while (rs.next()) {                    ProductData product  = new ProductData(rs.getString("pk"), rs.getString("product_name"), rs.getString("format"),                    rs.getString("regularity"), rs.getString("img_url"), rs.getString("brand_name"), rs.getString("producer_address"),                    rs.getString("shelf_life"), rs.getString("category_name"), rs.getString("ingredient"), rs.getString("brand_id"),                    rs.getString("producer_id"), rs.getString("category_code"), rs.getString("batch_id_list"), rs.getString("ingredient_id_list"));            System.err.println(product.toString());            System.err.println("\n=========================================================");        }        /* 关闭资源*/        rs.close();        pstmt.close();    }}

说明:

  1. 在利用 rs.getString("columnName")查询某一列值时,如果该列未定义,那么会报一个SQLException类型的异常:Undefined column. columnName=product_ids
  2. 如果该列没有值,那么 rs.getString("columnName") 将会返回null
1 0
原创粉丝点击