Java操作Hbase 创建、查询及删除

8 篇文章 0 订阅
8 篇文章 0 订阅

直接上代码:

package an.hbase.operation;

import java.io.IOException;
import java.util.Map;

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.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
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;

public class HbasicOperation {

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		/**init the configuration of Hbase*/
		Configuration conf = HBaseConfiguration.create();
		conf.set("hbase.zookeeper.quorun", "192.168.12.54");
		HBaseAdmin admin = new HBaseAdmin(conf);
		
		
		/**HBaseAdmin.create() 可以用来创建一张新表,该方法的参数为HTableDescription
		 * 用来描述表名和相关的列簇。该方法的返回值为HTable类,用于对表进行相关的操作
		 * */
		HTableDescriptor tableDescripter = new HTableDescriptor("tab1".getBytes());
		tableDescripter.addFamily(new HColumnDescriptor("fam1"));
		admin.createTable(tableDescripter);
		HTable table = new HTable(conf,"tab1");
		
		/**HTable.put()可以向表中插入数据,该方法的参数为Put类*
		 */
		Put putRow1 = new Put("row1".getBytes());
		putRow1 .add("fam1".getBytes(),"col1".getBytes(),"val1".getBytes());
		table.put(putRow1 );
		
		System.out.println("add row2");
		
		Put putRow2 = new Put("row2".getBytes());
		 putRow2.add("fam1".getBytes(), "col2".getBytes(), "val2".getBytes());
		 putRow2.add("fam1".getBytes(), "col3".getBytes(), "val3".getBytes());
		 table.put( putRow2);
		 
		 /**HTable.getScanner()可以获得某一个列族的所有数据,
		  * 该方法返回Result类,Result.getFamiliyAmp()可以获得
		  * 以列名为key,值为value的映射表,然后就可以以此读取相关的内容了
		  * */
		 for(Result row:table.getScanner("fam1".getBytes())){
			 System.out.format("ROW\t%s\n"	,	 new String(row.getRow()));
			 for(Map.Entry<byte[], byte[]> entry : row.getFamilyMap("fam1".getBytes()).entrySet()){
				 String column = new String(entry.getKey());
				 String value = new String(entry.getValue());
				 System.out.format("COLUMN\tfam1:%s\t%s\n", column,value);
			 }//for Map
		 }//for R
		 
		// admin.disableTable("tab1"); //disable the table
		 //admin.deleteTable("tab1");//delete the table
		 
		
		
		

	}

}

java -jar ...jar



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值