feat:优化表创建流程并添加数据库连接管理
- 在创建表之前检查表是否存在,如果存在则禁用并删除 - 新增 MyConnect 类用于管理 HBase 连接 - 优化了表创建过程,使其更加健壮
This commit is contained in:
parent
fd9875baee
commit
eefcadd7a4
@ -60,9 +60,17 @@ public class HBaseEmpManager {
|
||||
// 创建 HBase 表
|
||||
private static void createTable() throws IOException {
|
||||
TableName tableName = TableName.valueOf(TABLE_NAME);
|
||||
// 检查表格是否存在
|
||||
if (admin.tableExists(tableName)) {
|
||||
System.out.println("Table emp1520 already exists.");
|
||||
return;
|
||||
System.out.println("表 " + TABLE_NAME + " 已经存在,准备禁用并删除...");
|
||||
|
||||
// 禁用表格
|
||||
admin.disableTable(tableName);
|
||||
System.out.println("表 " + TABLE_NAME + " 已禁用。");
|
||||
|
||||
// 删除表格
|
||||
admin.deleteTable(tableName);
|
||||
System.out.println("表 " + TABLE_NAME + " 已删除。");
|
||||
}
|
||||
|
||||
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
|
||||
|
40
src/main/java/MyConnect.java
Normal file
40
src/main/java/MyConnect.java
Normal file
@ -0,0 +1,40 @@
|
||||
import org.apache.hadoop.conf.Configuration;
|
||||
import org.apache.hadoop.hbase.*;
|
||||
import org.apache.hadoop.hbase.client.*;
|
||||
import java.io.IOException;
|
||||
public class MyConnect{
|
||||
public static Configuration configuration;
|
||||
public static Connection connection;
|
||||
public static Admin admin;
|
||||
public static void main(String[] args)throws IOException{
|
||||
init();
|
||||
close();
|
||||
}
|
||||
//建立连接
|
||||
public static void init(){
|
||||
//根据 hbase-site.xml文件初始化Configuration 对象
|
||||
configuration = HBaseConfiguration.create();
|
||||
try{
|
||||
//根据 Configuration对象初始化Connection 对象
|
||||
connection = ConnectionFactory.createConnection(configuration);
|
||||
//获取Admin 对象实例
|
||||
admin = connection.getAdmin();
|
||||
}catch (IOException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("Connect to HBase Successfully!");
|
||||
}
|
||||
//关闭连接
|
||||
public static void close(){
|
||||
try{
|
||||
if(admin != null){
|
||||
admin.close();
|
||||
}
|
||||
if(null != connection){
|
||||
connection.close();
|
||||
}
|
||||
}catch (IOException e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user