Hbase 创建表

创建表

Pom

   <dependencies>
        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-server</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hbase</groupId>
            <artifactId>hbase-client</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.hadoop</groupId>
            <artifactId>hadoop-common</artifactId>
            <version>2.6.2</version>
            <scope>compile</scope>
        </dependency>
  </dependencies>

  

Java

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;

public class createTable {

    public static Connection conn;
    public static Configuration conf;

    static {

        conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum", "192.168.222.128");  //hbase 服务地址
        conf.set("hbase.zookeeper.property.clientPort", "2181"); //端口号

        try {
            conn = ConnectionFactory.createConnection(conf);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) throws Exception {

        String tableName = "studentTable";
        if(isTableExist(tableName))
        {
            createtable(tableName,"info");
        }
        System.out.println("end...");
    }

    public static void createtable(String tablename, String... ColumnFamilys) throws IOException {

        Admin admin = conn.getAdmin();
        /*if (admin != null) {
            try {
                //获取到数据库所有表信息
                HTableDescriptor[] allTable = admin.listTables();
                for (HTableDescriptor hTableDescriptor : allTable) {
                    System.out.println(hTableDescriptor.getNameAsString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/

        HTableDescriptor table = new HTableDescriptor(TableName.valueOf(tablename));
        for (String family : ColumnFamilys) {
            HColumnDescriptor columnfamily = new HColumnDescriptor(family);
            table.addFamily(columnfamily);
        }
        admin.createTable(table);

        System.out.println("create sucsssss");
    }


    public static boolean isTableExist(String tableName) throws MasterNotRunningException,
            ZooKeeperConnectionException, IOException{

        HBaseAdmin admin = new HBaseAdmin(conf);
        return admin.tableExists(tableName);
    }


}

  

posted @ 2020-02-17 11:28  抽象Java  阅读(1071)  评论(0编辑  收藏  举报