Hbase实验:java创建和删除table

开启zookeeper、hadoop、hbase:


打开eclipse创一个java project,然后导入所需jar包:

写好java代码,运行create,然后去hbase shell里查看:

运行delete:

package hh;

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.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;

public class ad {
    public static Configuration configuration;
  
    public static void main(String[] args) {  
        // createTable();
    	deleteTable();
     }  
  
    public static void createTable() {
        Configuration config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", "127.0.0.1");
        config.set("hbase.zookeeper.property.clientPort", "2181");

        Connection connection = null;
        Admin admin = null;

        try {
            connection = ConnectionFactory.createConnection(config);
            admin = connection.getAdmin();
            
            String tableName = "mytable";

            if (!admin.isTableAvailable(TableName.valueOf(tableName))) {
                HTableDescriptor hbaseTable = new HTableDescriptor(TableName.valueOf(tableName));
                hbaseTable.addFamily(new HColumnDescriptor("name"));
                hbaseTable.addFamily(new HColumnDescriptor("contact_info"));
                hbaseTable.addFamily(new HColumnDescriptor("personal_info"));
                admin.createTable(hbaseTable);
                }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (admin != null) {
                    admin.close();
                    }
                if (connection != null && !connection.isClosed()) {
                    connection.close();
                    }
            } catch (Exception e2) {
                e2.printStackTrace();
                }
           }
    }
    
    public static void deleteTable() {
    	  Configuration config = HBaseConfiguration.create();
        config.set("hbase.zookeeper.quorum", "127.0.0.1");
        config.set("hbase.zookeeper.property.clientPort", "2181");

        Connection connection = null;
        Admin admin = null;
        try {
        	   connection = ConnectionFactory.createConnection(config);
            admin = connection.getAdmin();
              
            String tableName = "mytable";
            admin.disableTable(TableName.valueOf(tableName));
            admin.deleteTable(TableName.valueOf(tableName));
        } catch(Exception e) {
            e.printStackTrace();
           }
    }
}
posted @ 2019-11-24 12:16  AlphaWA  阅读(553)  评论(0编辑  收藏  举报