HBase java API


前面介绍了HBase的shell命令操作,现在介绍Hbase java API操作。


开发环境:

IDE:Eclipse

hadoop:hadoop-1.1.2

hbase: hbase-0.94.7-security



1、获取Configuration

private static Configuration getConfiguration() {
	Configuration conf = HBaseConfiguration.create();
	conf.set("hbase.rootdir", "hdfs://hadoop0:9000/hbase");
	//在eclipse中必须添加这个属性值
	conf.set("hbase.zookeeper.quorum", "hadoop0");
	return conf;
}


2、创建表

private static void createTable(String tableName, String columnFamily) throws Exception{
	HBaseAdmin admin = new HBaseAdmin(getConfiguration());
	if (admin.tableExists(tableName)) {
		System.out.println("table exists.");
	} else {
		HTableDescriptor descriptor = new HTableDescriptor(tableName);
		descriptor.addFamily(new HColumnDescriptor(columnFamily));
		admin.createTable(descriptor);
		System.out.println("create table success!");
		}
}

3、添加一条记录

public static void putRec(String tableName, String row, String columnFamily,
		String column,String data) throws Exception {
	HTable hTable = new HTable(getConfiguration(), tableName);
	Put put = new Put(Bytes.toBytes(row));
	put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(data));
	hTable.put(put);
	System.out.println("rowkey =" + row + ",columnFamily = " 
		+ columnFamily + ", column = " + column
		+ ", data = " + data);
}


4、读取一条记录

public static void getRec(String tableName, String rowKey) throws IOException {
	HTable hTable = new HTable(getConfiguration(), tableName);
	Get get = new Get(Bytes.toBytes(rowKey));
	Result result = hTable.get(get);
	System.out.println("Get = " + result);
}


5、全表扫描

public static void scanTable (String tableName) throws Exception {
	HTable hTable = new HTable(getConfiguration(), tableName);
	Scan scan = new Scan();
	ResultScanner scanner =hTable.getScanner(scan);
	for (Result result : scanner) {
		System.out.println("scan--->" + result);
	}
}

6、删除表

public static void dropTable(String tableName) throws Exception {
	HBaseAdmin admin = new HBaseAdmin (getConfiguration());
	if (admin.tableExists(tableName)) {
	try {
		admin.disableTable(tableName);
		admin.deleteTable(tableName);
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("drop table " + tableName + "failed!!");
		}
	}
	System.out.println("drop table" + tableName + "success !!");
}

7、驱动代码

public static void main(String[] args) throws Exception {
	String tableName = "person";
	String columnFamily = "info";
	String rowKey = "robin";
		
	createTable(tableName, columnFamily);
		
	putRec(tableName, rowKey, columnFamily, "birthday", "1988-11-29");
	putRec(tableName, rowKey, columnFamily, "age", "12");
	getRec(tableName, rowKey);
	scanTable(tableName);
		
	dropTable(tableName);
}



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值