使用Phoenix的JDBC接口

使用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值