通過對HBase API的使用,下面例子舉例了常見對HBase的操作,如下所示:
package net.linuxidc.www;
-
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.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.BatchUpdate;
public class HBaseDBDao {
//定義配置對象HBaseConfiguration
static HBaseConfiguration cfg =null;
static {
Configuration configuration = new Configuration();
cfg = new HBaseConfiguration(configuration);
}
//創(chuàng)建一張表,指定表名,列族
public static void createTable(String tableName,String columnFarily)throws Exception{
HBaseAdmin admin = new HBaseAdmin(cfg);
if(admin.tableExists(tableName)){
System.out.println(tableName+"不存在!");
System.exit(0);
}else{
HTableDescriptor tableDesc = new HTableDescriptor(tableName);
tableDesc.addFamily(new HColumnDescriptor(columnFarily+":"));
System.out.println("創(chuàng)建表成功!");
}
}
//添加數(shù)據(jù),通過HTable。和BatchUpdate為已經(jīng)存在的表添加數(shù)據(jù)data
public static void addData(String tableName,String row,String columnFamily,String column,String data)throws Exception{
HTable table = new HTable(cfg,tableName);
BatchUpdate update = new BatchUpdate(row);
update.put(columnFamily+":"+column, data.getBytes());
table.commit(update);
System.out.println("添加成功!");
}
//顯示所有數(shù)據(jù),通過HTable Scan類獲取已有表的信息
public static void getAllData(String tableName)throws Exception{
HTable table = new HTable(cfg,tableName);
Scan scan = new Scan();
ResultScanner rs = table.getScanner(scan);
for(Result r:rs){
for(KeyValue kv:r.raw()){
System.out.println(new String(kv.getColumn())+new String(kv.getValue()));
}
}
}
//測試函數(shù)
public static void main(String[] args){
try{
String tableName = "student";
HBaseDBDao.createTable(tableName, "c1");
HBaseDBDao.addData(tableName, "row1", "c1", "1", "this is row 1 column c1:c1");
HBaseDBDao.getAllData(tableName);
}catch(Exception e){
e.printStackTrace();
}
}
} 本文出自:億恩科技【mszdt.com】
服務(wù)器租用/服務(wù)器托管中國五強!虛擬主機域名注冊頂級提供商!15年品質(zhì)保障!--億恩科技[ENKJ.COM]
|