6.3 创建表
涉及到表的元数据操作的都需要用 Admin
对象, 所以,我们把 Admin
对象提出来.
package com.atguigu.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.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import java.io.IOException;
public class HBaseDemo {
private static Configuration conf;
private static Connection conn;
private static Admin admin;
// 为了方便, 我们使用静态代码块来获取 HBaseConfiguration 对象
static {
// 创建 Configuration 对象
conf = HBaseConfiguration.create();
// 配置 Zookeeper
conf.set("hbase.zookeeper.quorum", "hadoop201");
conf.set("hbase.zookeeper.property.clientPort", "2181");
try {
conn = ConnectionFactory.createConnection(conf);
admin = conn.getAdmin();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
System.out.println(isTableExists("person"));
createTable("person", "info");
System.out.println(isTableExists("person"));
close();
}
/**
* @param tableName 表名
* @param cfs 多个列族
*/
private static void createTable(String tableName, String... cfs) throws IOException {
if(isTableExists(tableName)) return; // 表如果存在就直接结束方法
HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf(tableName));
for (String cf : cfs) {
descriptor.addFamily(new HColumnDescriptor(cf));
}
admin.createTable(descriptor);
System.out.println("表:" + tableName + "创建成功!");
}
/**
* 判断指定的表是否存在
*
* @param tableName
* @return
* @throws IOException
*/
private static boolean isTableExists(String tableName) throws IOException {
// 创建一个连接对象
boolean isExists = admin.tableExists(TableName.valueOf(tableName));
return isExists;
}
/**
* 关闭 Admin和 Connection 对象
*/
private static void close() {
if (admin != null) {
try {
admin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}