1. 程式人生 > >HBase學習-表的增刪改插

HBase學習-表的增刪改插

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.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/12/12 0012.
 */
public class HBase { private static final String TABLE_NAME = "stu_table"; private static final String FAMILY_NAME = "f1"; private static final String COLUMN_NAME = "name"; private static final String COLUMN_AGE = "age"; private static final String ROW_KEY1 = "r1"; private static final String ROW_KEY2 = "r2"
; public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); conf.set("hbase.rootdir", "hdfs://master:9000/hbase"); conf.set("hbase.zookeeper.quorum", "master:2181"); //create HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
if (!hBaseAdmin.tableExists(TABLE_NAME)) { HTableDescriptor hTableDescriptor = new HTableDescriptor(TABLE_NAME); hTableDescriptor.addFamily(new HColumnDescriptor(FAMILY_NAME)); hBaseAdmin.createTable(hTableDescriptor); System.out.println("table create success !"); } else { System.out.println("table exits"); } //insert HTable hTable = new HTable(conf, TABLE_NAME); List<Put> putList = new ArrayList<Put>(); Put put1 = new Put(ROW_KEY1.getBytes()); put1.add(FAMILY_NAME.getBytes(), COLUMN_NAME.getBytes(), "ylz".getBytes()); put1.add(FAMILY_NAME.getBytes(), COLUMN_AGE.getBytes(), "24".getBytes()); putList.add(put1); Put put2 = new Put(ROW_KEY2.getBytes()); put2.add(FAMILY_NAME.getBytes(), COLUMN_NAME.getBytes(), "pf".getBytes()); put2.add(FAMILY_NAME.getBytes(), COLUMN_AGE.getBytes(), "25".getBytes()); putList.add(put2); hTable.put(putList); //scan 一條 Get get = new Get(ROW_KEY1.getBytes()); Result result = hTable.get(get); String name1 = new String(result.getValue(FAMILY_NAME.getBytes(), COLUMN_NAME.getBytes())); String age1 = new String(result.getValue(FAMILY_NAME.getBytes(), COLUMN_AGE.getBytes())); System.out.println("name:" + name1 + "\t age1:" + age1); //scan 多條 Scan scan = new Scan(); //限制起始行和結束行 // scan.setStartRow(ROW_KEY1.getBytes()); // scan.setStopRow(ROW_KEY2.getBytes()); ResultScanner scanner = hTable.getScanner(scan); //迭代 for (Result rs : scanner) { String rowKey = new String(result.getRow()); String name = new String(result.getValue(FAMILY_NAME.getBytes(), COLUMN_NAME.getBytes())); String age = new String(result.getValue(FAMILY_NAME.getBytes(), COLUMN_AGE.getBytes())); System.out.println(rowKey + "\t" + "name:" + name + "\t age:" + age); } //delete 一行 Delete delete = new Delete(ROW_KEY1.getBytes()); hTable.delete(delete); //對錶的刪除 hBaseAdmin.disableTable(TABLE_NAME); hBaseAdmin.deleteTable(TABLE_NAME); } }