feat:优化表创建流程并添加数据库连接管理

- 在创建表之前检查表是否存在,如果存在则禁用并删除
- 新增 MyConnect 类用于管理 HBase 连接
- 优化了表创建过程,使其更加健壮
This commit is contained in:
fly6516 2025-03-26 10:38:14 +08:00
parent fd9875baee
commit eefcadd7a4
2 changed files with 50 additions and 2 deletions

View File

@ -60,9 +60,17 @@ public class HBaseEmpManager {
// 创建 HBase // 创建 HBase
private static void createTable() throws IOException { private static void createTable() throws IOException {
TableName tableName = TableName.valueOf(TABLE_NAME); TableName tableName = TableName.valueOf(TABLE_NAME);
// 检查表格是否存在
if (admin.tableExists(tableName)) { if (admin.tableExists(tableName)) {
System.out.println("Table emp1520 already exists."); System.out.println("" + TABLE_NAME + " 已经存在,准备禁用并删除...");
return;
// 禁用表格
admin.disableTable(tableName);
System.out.println("" + TABLE_NAME + " 已禁用。");
// 删除表格
admin.deleteTable(tableName);
System.out.println("" + TABLE_NAME + " 已删除。");
} }
HTableDescriptor tableDescriptor = new HTableDescriptor(tableName); HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);

View 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();
}
}
}