wiki:NCHCCloudCourse100929_4_HBEX2

Version 1 (modified by waue, 14 years ago) (diff)

--

HBase 進階課程
程式範例練習

上一關 < 第二關 > 下一關

範例二: Put 資料進 Column

package org.nchc.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.util.GenericOptionsParser;

public class PutData {
  public PutData(String tablename, String row, String family, String column,
      String value) {
    try {
      putData(tablename, row, family, column, value);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  static public void putData(String tablename, String row, String family,
      String column, String value) throws IOException {
    // HBaseConfiguration 能接收 hbase-site.xml 的設定值
    HBaseConfiguration config = new HBaseConfiguration();
    // 檔案的操作則使用 HBaseAdmin
    HTable table = new HTable(config, tablename);

    byte[] brow = Bytes.toBytes(row);
    byte[] bfamily = Bytes.toBytes(family);
    byte[] bcolumn = Bytes.toBytes(column);
    byte[] bvalue = Bytes.toBytes(value);

    Put p = new Put(brow);
    p.add(bfamily, bcolumn, bvalue);

    table.put(p);
    System.out.println("Put data :\"" + value + "\" to Table: " + tablename
        + "'s " + family + ":" + column);

    table.close();
  }

  static public void main(String argv[]) throws IOException {
    
    String[] args = new GenericOptionsParser(new Configuration(), argv)
        .getRemainingArgs();
    if (args.length < 5) {
      System.out.println("PutData <TableName> <Row> <Family> <Qualifier> <Value>");
      return;
    }
    putData(args[0],args[1],args[2],args[3],args[4]);
  }
}