分享

Phoenix系列入门(三)JDBC CRUD操作

yr123 2015-9-9 15:56:42 发表于 连载型 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 2 58679
本帖最后由 pig2 于 2015-9-10 16:19 编辑
问题导读
1、如何使用JDBC的方式来对HBase中的数据进行CRUD操作?
2、HBase使用JDBC需要哪些配置?




1. 说明
本篇主要介绍使用JDBC的方式来对HBase中的数据进行CRUD操作,项目为maven项目。请自行将phoenix-4.2.2-client.jar(可以在下载的phoenix-4.2.2-bin.tar.gz中找到该jar包)添加到项目的classpath中,将HBase集群的hbase-site.xml配置文件添加到项目的resources目录下。为了查看日志输出配置了一个简单的log4j.properties,也一并放到resources目录下。
log4j.properties 内容如下:
log4j.rootLogger=WARN, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

2. 获得连接
/**
  * project:hadoop-phoenix
  * file:BaseDB.java
  * time:2015年5月4日 下午2:19:57
  * description:
  */
package cn.com.dimensoft.hadoop.phoenix.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;

/**
* class: BaseDB
* package: cn.com.dimensoft.hadoop.phoenix.jdbc
* time: 2015年5月4日 下午2:19:57
* description:
*/
public class BaseDB {

    /**
     *
     * name:getConnection
     * time:2015年5月6日 下午2:07:06
     * description: get JDBC connection
     * @return connection
     */
    public static Connection getConnection() {
        try {
            // load driver
            Class.forName("org.apache.phoenix.jdbc.PhoenixDriver");

            // get connection
            // jdbc 的 url 类似为 jdbc:phoenix [ :<zookeeper quorum> [ :<port number> ] [ :<root node> ] ],
            // 需要引用三个参数:hbase.zookeeper.quorum、hbase.zookeeper.property.clientPort、and zookeeper.znode.parent,
            // 这些参数可以缺省不填而在 hbase-site.xml 中定义。
            return DriverManager.getConnection("jdbc:phoenix");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}

3. 创建表
/**
     *
     * name:create
     * time:2015年5月4日 下午2:58:31
     * description:create table
     */
    public static void create() {
        Connection conn = null;
        try {
            // get connection
            conn = BaseDB.getConnection();

            // check connection
            if (conn == null) {
                System.out.println("conn is null...");
                return;
            }

            // check if the table exist
            ResultSet rs = conn.getMetaData().getTables(null, null, "USER",
                    null);
            if (rs.next()) {
                System.out.println("table user is exist...");
                return;
            }
            // create sql
            String sql = "CREATE TABLE user (id varchar PRIMARY KEY,INFO.account varchar ,INFO.passwd varchar)";

            PreparedStatement ps = conn.prepareStatement(sql);

            // execute
            ps.execute();
            System.out.println("create success...");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

4. 插入数据
/**
     *
     * name:insert
     * time:2015年5月4日 下午2:59:11
     * description:
     */
    public static void upsert() {

        Connection conn = null;
        try {
            // get connection
            conn = BaseDB.getConnection();

            // check connection
            if (conn == null) {
                System.out.println("conn is null...");
                return;
            }

            // create sql
            String sql = "upsert into user(id, INFO.account, INFO.passwd) values('001', 'admin', 'admin')";

            PreparedStatement ps = conn.prepareStatement(sql);

            // execute upsert
            String msg = ps.executeUpdate() > 0 ? "insert success..."
                    : "insert fail...";

            // you must commit
            conn.commit();
            System.out.println(msg);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

5. 查询数据
/**
     *
     * name:query
     * time:2015年5月4日 下午3:58:12
     * description:query data
     */
    public static void query() {

        Connection conn = null;
        try {
            // get connection
            conn = BaseDB.getConnection();

            // check connection
            if (conn == null) {
                System.out.println("conn is null...");
                return;
            }

            // create sql
            String sql = "select * from user";

            PreparedStatement ps = conn.prepareStatement(sql);

            ResultSet rs = ps.executeQuery();

            System.out.println("id" + "\t" + "account" + "\t" + "passwd");
            System.out.println("======================");

            if (rs != null) {
                while (rs.next()) {
                    System.out.print(rs.getString("id") + "\t");
                    System.out.print(rs.getString("account") + "\t");
                    System.out.println(rs.getString("passwd"));
                }
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

6. 更新数据
更新数据的操作与插入数据相同

7.删除数据
/**
     *
     * name:delete
     * time:2015年5月4日 下午4:03:11
     * description:delete data
     */
    public static void delete() {

        Connection conn = null;
        try {
            // get connection
            conn = BaseDB.getConnection();

            // check connection
            if (conn == null) {
                System.out.println("conn is null...");
                return;
            }

            // create sql
            String sql = "delete from user where id='001'";

            PreparedStatement ps = conn.prepareStatement(sql);

            // execute upsert
            String msg = ps.executeUpdate() > 0 ? "delete success..."
                    : "delete fail...";

            // you must commit
            conn.commit();
            System.out.println(msg);

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

8. 删除表
/**
     *
     * name:drop
     * time:2015年5月4日 下午4:03:35
     * description:drop table
     */
    public static void drop() {

        Connection conn = null;
        try {
            // get connection
            conn = BaseDB.getConnection();

            // check connection
            if (conn == null) {
                System.out.println("conn is null...");
                return;
            }

            // create sql
            String sql = "drop table user";

            PreparedStatement ps = conn.prepareStatement(sql);

            // execute
            ps.execute();

            System.out.println("drop success...");

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }


上一篇:

Phoenix系列入门(二)CLI CRUD操作




下一篇:
Phoenix系列入门(四)配置使用Squirrel GUI连接Phoenix









已有(2)人评论

跳转到指定楼层
xuanxufeng 发表于 2015-9-10 15:59:24
补充:JDBC 无法添加数据



在使用phoenix的JDBC驱动连接HBase,进行数据添加的时候发现数据总是无法插入,并且log日志也没有任何报错信息,最后发现是没有手动commit的缘故,phoenix并没有帮我们做commit的操作,需要我们自己手动commit。最后在执行executeUpdate后添加commit代码后数据被成功插入。

回复

使用道具 举报

chyeers 发表于 2015-9-19 10:19:47
本帖最后由 chyeers 于 2015-9-19 10:21 编辑
xuanxufeng 发表于 2015-9-10 15:59
补充:JDBC 无法添加数据

我使用 批处理一次性插入 ,但是有时候 phoenix 会爆出异常 [mw_shl_code=shell,true]org.apache.phoenix.exception.BatchUpdateExecution: ERROR 1106 (XCL06): Exception while executing batch[/mw_shl_code]
这样就丢失数据了,请问楼主遇到过么?
[mw_shl_code=scala,true] def toPhoenix(queue:mutable.Queue[Array[String]]): Unit = {
    val manager:DBConnectionManager  = DBConnectionManager.getInstance()
    val conn:Connection  = manager.getConnection("phoenix")
    var ps: PreparedStatement = null
    var flag:Boolean = false
    val sql = "UPSERT INTO DATA.LOG VALUES(?,?,?,?,?)"
    try{
      ps = conn.prepareStatement(sql)
      for(i<- 0 to queue.length-1){
        ps.setString(1, queue(i)(0))
        ps.setString(2, queue(i)(1))
        ps.setString(3, queue(i)(2))
        ps.setString(4, queue(i)(3))
        ps.setString(5, queue(i)(4))
        ps.addBatch()
      }
      ps.executeBatch()
      conn.commit()
      flag = true
    }catch {
      case e: Exception => print(e)
......[/mw_shl_code]

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条