HBase table Put 插入数据

HBase 版本: 1.2.1

package com.feng.hbase;

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class PutData {

    public static void main(String[] args) {
        String talbeName = "test1";
        String columnFamily = "cf";
        String attribute = "attribute" + Math.random();
        String rowkey = "row-" + Math.random();
        String data = String.valueOf(Math.random());

        Connection connection = null;
        Table table = null;
        try {
            Configuration config = HBaseConfiguration.create();
            config.set("hbase.zookeeper.quorum", "localhost");
            connection = ConnectionFactory.createConnection(config);

            // 获取表对象
            table = connection.getTable(TableName.valueOf(talbeName));

            if (table != null) {
                Put put = new Put(Bytes.toBytes(rowkey));
                put.addColumn(Bytes.toBytes(columnFamily),
                        Bytes.toBytes(attribute), Bytes.toBytes(data));
                table.put(put);

                put = new Put(Bytes.toBytes(rowkey));
                put.addColumn(Bytes.toBytes(columnFamily),
                        Bytes.toBytes(attribute + "-01"), Bytes.toBytes(data));
                table.put(put);

                System.out.println(talbeName + " create success!");
            } else {
                System.out.println("There is not " + talbeName);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (table != null) {
                try {
                    table.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

版权声明:本文为dongbeiMan原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。