HBase的JavaAPI使用

来源:互联网 发布:安卓字体软件下载 编辑:程序博客网 时间:2024/06/01 07:44

Java Client API Overview

HBase是用Java写的,支持用编程语言来动态操作管理数据库,能用命令行做的都可以用API来做。

基本的使用过程如下:

1.创建一个 Configuration 对象
–从 HDFS 对象中调用 Configuration 
–添加 HBase 属性

Configuration conf = HbaseConfiguration.create();
2.创建 HTable
–提供 Configuration 对象
–提供 表名

HTable hTable = new HTable(conf, tableName);
3.执行操作
–如 put, get, scan, delete, etc...

hTable.getTableName();
4.关闭 HTable 实例
–清空缓存
–释放资源

hTable.close();

下面是一个建表的例子:

import java.io.IOException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.hbase.HBaseConfiguration;import org.apache.hadoop.hbase.client.HTable;import org.apache.hadoop.hbase.util.Bytes;public class  ConstructHTable{public static void main(String[] args) throws IOException{Configuration conf = HBaseConfiguration.create();HTable htable = new HTable(conf,"table-created_from_api");System.out.println("Table :"+Bytes.toString(htable.getTableName()));htable.close();}}

下面是插入数据的例子:

import java.io.IOException;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.hbase.HBaseConfiguration;import org.apache.hadoop.hbase.client.HTable;import org.apache.hadoop.hbase.client.Put;import static org.apache.hadoop.hbase.util.Bytes.*;public class PutExample {public static void main(String[] args) throws IOException {Configuration conf = HBaseConfiguration.create();HTable hTable = new HTable(conf, "HBaseSamples");Put put1 = new Put(toBytes("row1"));put1.add(toBytes("test"), toBytes("col1"), toBytes("val1"));put1.add(toBytes("test"), toBytes("col2"), toBytes("val2"));hTable.put(put1);hTable.close();}}


0 0