java操作HBase

转载:www.linuxidc.com/Linux/2014-03/97535.htm

加载hadoop,HBase所需要的包

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;


public class HBaseAPP {


private static final String TABLE_NAME = "table1";
private static final String FAMILY_NAME = "family1";
private static final String ROW_KEYS = "rowKey1";


public static void main(String[] args) throws Exception {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://znb:9000/hbase");
// 使用eclipse时必须添加这个,否则无法定位
conf.set("hbase.zookeeper.quorum", "znb");

// HBaseAdmin用来创建表 删除表使用 alt+shift+l 抽取变量
HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
// 创建表
createTable(hBaseAdmin);
// 删除表
// deleteTable(hBaseAdmin);
 
// HTable 插入 查询 使用
HTable hTable = new HTable(conf, TABLE_NAME);
// 插入记录
putRecord(hTable);
// 查询记录
getRecord(hTable);
// 扫面
scanRecord(hTable);
}


private static void scanRecord(HTable hTable) throws IOException {
Scan scan = new Scan();
ResultScanner scanner = hTable.getScanner(scan);
for (Result result : scanner) {
byte[] value = result.getValue(FAMILY_NAME.getBytes(),
"age".getBytes());
System.out.println(result + "\t" + new String(value));
}
}


private static void getRecord(HTable hTable) throws IOException {
Get get = new Get(ROW_KEYS.getBytes());
Result result = hTable.get(get);
byte[] value = result
.getValue(FAMILY_NAME.getBytes(), "age".getBytes());
System.out.println(new String(value));
}


private static void putRecord(HTable hTable) throws IOException {
Put put = new Put(ROW_KEYS.getBytes());
put.add(FAMILY_NAME.getBytes(), "age".getBytes(), "28".getBytes());
hTable.put(put);
hTable.close();
}


private static void deleteTable(final HBaseAdmin hBaseAdmin)
throws IOException {
hBaseAdmin.disableTable(TABLE_NAME);
hBaseAdmin.deleteTable(TABLE_NAME);
}


private static void createTable(HBaseAdmin hBaseAdmin) throws IOException {
if (!(hBaseAdmin.tableExists(TABLE_NAME))) {
HTableDescriptor hTableDescriptor = new HTableDescriptor(TABLE_NAME);
HColumnDescriptor family = new HColumnDescriptor(FAMILY_NAME);
hTableDescriptor.addFamily(family);
hBaseAdmin.createTable(hTableDescriptor);
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值