import java.io.IOException;
import java.util.ArrayList;
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.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 HBaseDemo001 {
public static void main(String[] args) throws Exception{
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://chaigy:9000/hbase");
//使用eclipse時必須添加這個,否則無法定位
conf.set("hbase.zookeeper.quorum", "chaigy");
HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
//建立表
if(!hBaseAdmin.isTableAvailable("test".getBytes())){
createTable(hBaseAdmin);
}else{
//deleteTable(hBaseAdmin);
}
//增加資料
HTable hTable = new HTable(conf, "test");
//putData(hTable);
//查詢資料
//findAll(hTable);
//修改資料
//updateData(hTable);
//查詢單挑資料
Get get = new Get("xiaoming".getBytes());
get.addColumn("testaddress".getBytes(), "city".getBytes());
Result result = hTable.get(get);
System.out.println(new String (result.getValue("testaddress".getBytes(), "city".getBytes())));
}
private static void updateData(HTable hTable) throws IOException {
Put put= new Put("xiaoming".getBytes());
put.add("testaddress".getBytes(),"city".getBytes(), "shanghai".getBytes());
hTable.put(put);
}
private static void findAll(HTable hTable) throws IOException {
Scan scan = new Scan();
ResultScanner result = hTable.getScanner(scan);
for (Result result2 : result) {
byte[] value = result2.getValue("testaddress".getBytes(), "city".getBytes());
System.out.println(result2+"****"+new String(value));
}
}
private static void putData(HTable hTable) throws IOException {
List<Put> list = new ArrayList<Put>();
Put puts =null;
for(int i=0;i<5;i++){
puts= new Put(("xiaoming"+i).getBytes());
puts.add("testaddress".getBytes(), ("city"+i).getBytes(), ("beijing"+i).getBytes());
list.add(puts);
}
hTable.put(list);
}
private static void deleteTable(HBaseAdmin hBaseAdmin) throws IOException {
System.out.println("0000000000");
//删除表
hBaseAdmin.disableTable("test".getBytes());
hBaseAdmin.deleteTable("test".getBytes());
}
private static void createTable(HBaseAdmin hBaseAdmin) throws IOException {
HTableDescriptor desc = new HTableDescriptor("test");
HColumnDescriptor family = new HColumnDescriptor("testinfo".getBytes());
HColumnDescriptor family1 = new HColumnDescriptor("testaddress".getBytes());
desc.addFamily(family);
desc.addFamily(family1);
hBaseAdmin.createTable(desc);
}
}