HBase简单API操作

这个博客展示了如何使用HBase Java API进行基本操作,包括创建表、插入数据和扫描表。示例代码中创建了一个名为'htableTest'的表,并在'info'列簇下插入了一条记录,然后进行了范围扫描。
摘要由CSDN通过智能技术生成

package com.ls.hbase;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.List;

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.KeyValue;
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.RetriesExhaustedWithDetailsException;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.util.Bytes;

public class HBaseApp {

 static String TABLE_NAME = "htableTest";//表名称
 static String familyName = "info";//列簇名称
 
 public static void main(String[] args) throws Exception{
  Configuration conf = HBaseConfiguration.create();
  conf.setStrings("hbase.zookeeper.quorum", "server2");
  scan(conf);
 }


 /***
  * 新增数据
  * @param conf
  * @throws IOException
  * @throws InterruptedIOException
  * @throws RetriesExhaustedWithDetailsException
  */
 private static void insert(Configuration conf) throws Exception{
  HTable htable = new HTable(conf,TABLE_NAME);
  
  //指定ROWKEY的值
  Put put = new Put(Bytes.toBytes("xiaoming"));
  //指定列簇名称、列修饰符、列值
  put.add(familyName.getBytes(), "age".getBytes(), "24".getBytes());
  htable.put(put);
 }


 /***
  * 创建/删除表语句
  * @param conf
  * @throws Exception
  */
 private static void createOrDelete(Configuration conf)throws Exception {
  HBaseAdmin admin = new HBaseAdmin(conf);
  HTableDescriptor htableDes = new HTableDescriptor(TABLE_NAME);
  HColumnDescriptor familyDesc = new HColumnDescriptor(familyName);
  htableDes.addFamily(familyDesc);
  //如果表不存在则创建表
  if(!admin.tableExists(TABLE_NAME)){
   admin.createTable(htableDes);
  }
  
  //删除表(先将表进行disable处理,然后才能delete操作)
//  admin.disableTable(TABLE_NAME);
//  admin.deleteTable(TABLE_NAME);
  
  //关闭操作
  admin.close();
  
 }
 
 
 /***
  * 浏览表
  * @param conf
  * @throws IOException
  */
 private static void scan(Configuration conf) throws IOException {
  HTable table = new HTable(conf,TABLE_NAME);
  
  Scan scan = new Scan();
  scan.setStartRow("xiaohua".getBytes());
  scan.setStopRow("xiaohua2".getBytes());
  
  //全表扫描
  ResultScanner scanner = table.getScanner(scan);
  
  for(Result result :scanner){
   List<KeyValue> column = result.getColumn("info".getBytes(), "age".getBytes());
   System.out.println(column);
  }
 }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值