翻译自HBase_in_action
2.1.3建立连接
Configuration conf=new HBaseConfiguration.create();
conf.set("hbase.zookeeper.quonum",serverip); //serverip为在配置文件中配置的master的ip地址
con.set("hbase.zookeeper.property.clientPort","2181"); //如果你在配置文件中更改过端口,通过这里进行设置,默认为2181端口
HTableInterface usersTable=new HTable(conf,"users"); //这样就可以从hbase中获得users表,这个操作的前提是users表已经建立,不然会报错
2.1.4 连接的管理
如果通过连接获取多张表,则可以通过HTablePool来进行管理
HTablePool pool=new HTablePool();
HTableInterface usersTable=pool.getTable("users");
..........
pool.close();
2.2 数据操作
2.2.1 添加数据
HTableInterface userstable=new HTable("users");
Put p=new Put(Bytes.toByte("wang"));
p.add(Bytes.toByte("info"),Bytes.toByte("email"),Bytes.toByte("wang@163.com"));
usertable.put(p);
usertable.close();
2.2.2 修改数据
HTableInterface userstable=new HTable("users");
Put p=new Put(Bytes.toByte("wang"));
p.add(Bytes.toByte("info"),Bytes.toByte("email"),Bytes.toByte("zhangzhangzhangzhang@163.com"));
usertable.put(p);
usertable.close();
2.2.3 读取数据
获得一条记录
- HTable table = new HTable(conf, tableName);
- Get get = new Get(Bytes.toBytes(row));
- Result result = table.get(get);
- // 输出结果
- for (KeyValue rowKV : result.raw()) {
- System.out.print("Row Name: " + new String(rowKV.getRow()) + " ");
- System.out.print("Timestamp: " + rowKV.getTimestamp() + " ");
- System.out.print("column Family: " + new String(rowKV.getFamily()) + " ");
- System.out.print("Row Name: " + new String(rowKV.getQualifier()) + " ");
- System.out.println("Value: " + new String(rowKV.getValue()) + " ");
- }
- 获得多条记录
- public static void getAllRows(String tableName) throws Exception {
- HTable table = new HTable(conf, tableName);
- Scan scan = new Scan();
- ResultScanner results = table.getScanner(scan);
- // 输出结果
- for (Result result : results) {
- for (KeyValue rowKV : result.raw()) {
- System.out.print("Row Name: " + new String(rowKV.getRow()) + " ");
- System.out.print("Timestamp: " + rowKV.getTimestamp() + " ");
- System.out.print("column Family: " + new String(rowKV.getFamily()) + " ");
- System.out
- .print("Row Name: " + new String(rowKV.getQualifier()) + " ");
- System.out.println("Value: " + new String(rowKV.getValue()) + " ");
- }
- }
- }