大数据hadoop学习【9】-----通过JAVA语言编程,实现对Hbase数据库表及数据的相关操作


上次的hadoop学习,我们了解了如何通过Hbase的shell界面相关shell命令,对数据库中表及表中数据进行操作!
但其实在很多时候,我们需要的是通过程序编程,完成与用户的界面交互功能,肯定不能让用户来进行shell命令进行相关数据的操作吧,这时候,我们需要通过Java语言来进行对Hbase的数据库的访问操作,本次博客,林君学长主要带大家了解,如何通过JAVA编程,来对HBase数据库进行访问并且操作

  • 操作系统:ubuntuKylin-16.04
  • hadoop版本:hadoop-2.7.7
  • hbase版本:hbase-1.4.13
  • java版本:jdk-1.7

一、Hbase数据库的运行

1、运行SSH

1)、新建终端,输入以下命令切换hadoop账户,然后运行ssh

su - hadoop
ssh localhost

在这里插入图片描述

2、运行hadoop

1)、终端输入以下命令,运行hadoop

start-dfs.sh
jps

在这里插入图片描述

3、运行Hbase

1)、当前终端输入如下命令,运行Hbase

start-hbase.sh
jps

在这里插入图片描述

上面三步执行之后,便可以隐藏终端,不要关闭哦!

二、eclipse整体Java项目介绍

1、创建属于hbase的Java Project

在这里插入图片描述

记住上面的JSE的选择,一定要选择1.5版本,因为后面的代码需要这个版本的,高于版本的不支持有些代码,需要自己重新编写!

2、导入Hbase所需要的基本库

1)、找到安装hbase路径的地方,然后导入路径 /usr/local/hbase/lib文件中的所有的库:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

3、创建相关的包、类

在这里插入图片描述

三、通过JAVA编程,实现对Hbase数据库的连接与关闭 ,已经菜单函数的编写

1、通过Java编程实现对Hbase数据库的连接

1)、java代码如下所示:

//建立连接
    public static void init(){
        configuration  = HBaseConfiguration.create();
        configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
        try{
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

2、通过Java编程实现对Hbase数据库的关闭

1)、java代码如下所示:

//关闭连接
    public static void close(){
        try{
            if(admin != null){
                admin.close();
            }
            if(null != connection){
                connection.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

3、菜单交互界面主函数

1)、java代码如下所示:

public static void main(String[] args) throws IOException{
		HDataBase h1=new HDataBase();
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		while(true){
			System.out.println("**********************基于JAVA的Hbase数据库表及表的基本操作**********************");
			System.out.println("1、向Hbase数据库创建一张表");
			System.out.println("2、查看数据库中已存在的表");
			System.out.println("3、为创建的表的某一行的某一列插入数据");
			System.out.println("4、根据行键rowkey查找数据");
			System.out.println("5、删除表中的数据");
			System.out.println("6、删除指定表");
			System.out.println("0、退出!");
			System.out.print("请输入你的选择:");
			int a=in.nextInt();
			switch(a){
			case 1: h1.createTable("Score",new String[]{"sname","course"});break;
			case 2: h1.listTables();break;
			case 3: h1.insertRow("Score", "10001", "sname"," ","chenYiYue");break;
			case 4: h1.getData("Score", "10001", "sname", " ");break;
			case 5: h1.deleteRow("Score", "10001", "sname", "chenYiYue");break;
			case 6: h1.deleteTable("Score");break;
			case 0:break;
			}
		}
	}

2)、运行结果如下:
在这里插入图片描述

四、Java编程实现对Hbase数据库表操作

1、通过JAVA编程,实现对Hbase数据库表的创建

1)、java程序如下所示:

public void createTable(String myTableName,String[] colFamily) throws IOException {
        init();
        TableName tableName = TableName.valueOf(myTableName);
        if(admin.tableExists(tableName)){
            System.out.println("该表已经存在!");
        }else {
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
            for(String str:colFamily){
                HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
                hTableDescriptor.addFamily(hColumnDescriptor);
            }
            admin.createTable(hTableDescriptor);
            System.out.println("表创建成功!");
        }
        close();
    }

通过输入需要穿件的表名,以及包括的列名组,来进行hbase表的创建
如:createTable(“Score”,new String[]{“sname”,“course”})
2)、运行结果如下所示:
在这里插入图片描述
3)、在终端进入hbase的shell界面,通过shell命令查询该表是否完成创建

hbase shell
list

在这里插入图片描述
可以看出,上表Score已经完成创建!

2、通过JAVA编程,实现对Hbase数据库表的查询

1)、java代码如下所示:

public void listTables() throws IOException {
        init();
        HTableDescriptor hTableDescriptors[] = admin.listTables();
        for(HTableDescriptor hTableDescriptor :hTableDescriptors){
            System.out.println(hTableDescriptor.getNameAsString());
        }
        close();
    }

上面函数的主要功能就是查询出Hbase数据库中的所有表,并在终端显示出来
2)、运行结果如下所示:
在这里插入图片描述
3)、终端查询是否一致
在这里插入图片描述
上图可以看出,完全一致!

3、通过JAVA编程,实现对Hbase数据库表的删除

1)、java代码如下所示:

public void deleteTable(String tableName) throws IOException {
        init();
        TableName tn = TableName.valueOf(tableName);
        if (admin.tableExists(tn)) {
            admin.disableTable(tn);
            admin.deleteTable(tn);
            System.out.println("表:"+tableName+"已成功删除");
        }
        close();
    }

通过输入Hbase的表名,完成对数据库表的删除,如:deleteTable(“Score”)
2)、运行结果如下所示:
在这里插入图片描述
3)、在shell界面查询是否删除成功
在这里插入图片描述
终端已经没有该表了!以上步骤建议在完成以下数据操作步骤后执行!

五、Java实现对数据库表中数据的操作

1、通过JAVA编程,实现对Hbase数据库表中数据的插入

1)、java代码如下所示:

public void insertRow(String tableName,String rowKey,String colFamily,String col,String val) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes());
        put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
        System.out.println("数据插入成功");
        table.put(put);
        table.close();
        close();
    }

通过输入表名、行键(可以理解为主键,主键唯一)、列族名、列族名下的列名、已经插入的数据进行表中数据的插入,如:insertRow(“Score”, “10001”, “sname”," ",“chenYiYue”),由于sname下面没有其他的列名,所以我们输入空就行
2)、运行结果如下所示:
在这里插入图片描述
3)、shell界面查询是否成功插入数据

get 'Score','10001'

在这里插入图片描述
数据已成功插入!

2、通过JAVA编程,实现对Hbase数据库表中数据的查询

1)、java代码如下所示:

public void getData(String tableName,String rowKey,String colFamily,String col)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        get.addColumn(colFamily.getBytes(),col.getBytes());
        Result result = table.get(get);
        showCell(result);
        table.close();
        close();
    }
public void showCell(Result result){
        Cell[] cells = result.rawCells();
        for(Cell cell:cells){
            System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
            System.out.println("Timetamp:"+cell.getTimestamp()+" ");
            System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
            System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
        }
    }

通过输入表名、行键(主键)、以及列族名,和列族名下的列名,如:
getData(“Score”, “10001”, “sname”," "),由于该sname列名下没有列名,所以我们输入空
2)、查询的结果如下所示:
在这里插入图片描述
3)、在shell界面查看查询的内容是否一致

get 'Score','10001','sname'

在这里插入图片描述
可以看出,完全一致!

3、通过JAVA编程,实现对Hbase数据库表中数据的删除

1)、java代码如下所示:

public void deleteRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(rowKey.getBytes());
        //删除指定列族的所有数据
        //delete.addFamily(colFamily.getBytes());
        //删除指定列的数据
        //delete.addColumn(colFamily.getBytes(), col.getBytes());
 
        table.delete(delete);
        System.out.println("信息已经删除");
        table.close();
        close();
    }

通过指定表名、行键(主键唯一)、列族名、和列族名下的数据进行数据的删除,如:deleteRow(“Score”, “10001”, “sname”, “chenYiYue”)
2)、运行结果如下所示:
在这里插入图片描述
3)、在shell界面查询该条数据是否删除成功:

get 'Score','10001','sname'

在这里插入图片描述
可以看出,sname下的数据chenyiyue已经被成功删除,该列下已经没有数据了!

六、项目整体代码

1、菜单类

package view;

import hbaseFile.HDataBase;
import java.io.IOException;
import java.util.Scanner;
public class Menu {
	public static void main(String[] args) throws IOException{
		HDataBase h1=new HDataBase();
		@SuppressWarnings("resource")
		Scanner in = new Scanner(System.in);
		while(true){
			System.out.println("**********************基于JAVA的Hbase数据库表及表的基本操作**********************");
			System.out.println("1、向Hbase数据库创建一张表");
			System.out.println("2、查看数据库中已存在的表");
			System.out.println("3、为创建的表的某一行的某一列插入数据");
			System.out.println("4、根据行键rowkey查找数据");
			System.out.println("5、删除表中的数据");
			System.out.println("6、删除指定表");
			System.out.println("0、退出!");
			System.out.print("请输入你的选择:");
			int a=in.nextInt();
			switch(a){
			case 1: h1.createTable("Score",new String[]{"sname","course"});break;
			case 2: h1.listTables();break;
			case 3: h1.insertRow("Score", "10001", "sname"," ","chenYiYue");break;
			case 4: h1.getData("Score", "10001", "sname", "chenYiYue");break;
			case 5: h1.deleteRow("Score", "10001", "sname", "chenYiYue");break;
			case 6: h1.deleteTable("Score");break;
			case 0:break;
			}
		}
	}
}

2、Hbase数据库操作类

package hbaseFile;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
 
public class HDataBase{
    public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;
    //建立连接
    public static void init(){
        configuration  = HBaseConfiguration.create();
        configuration.set("hbase.rootdir","hdfs://localhost:9000/hbase");
        try{
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    //关闭连接
    public static void close(){
        try{
            if(admin != null){
                admin.close();
            }
            if(null != connection){
                connection.close();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
 
    /**
     * 建表。HBase的表中会有一个系统默认的属性作为主键,主键无需自行创建,默认为put命令操作中表名后第一个数据,因此此处无需创建id列
     * @param myTableName 表名
     * @param colFamily 列族名
     * @throws IOException
     */
    public void createTable(String myTableName,String[] colFamily) throws IOException {
        init();
        TableName tableName = TableName.valueOf(myTableName);
        if(admin.tableExists(tableName)){
            System.out.println("该表已经存在!");
        }else {
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
            for(String str:colFamily){
                HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
                hTableDescriptor.addFamily(hColumnDescriptor);
            }
            admin.createTable(hTableDescriptor);
            System.out.println("表创建成功!");
        }
        close();
    }
    /**
     * 删除指定表
     * @param tableName 表名
     * @throws IOException
     */
    public void deleteTable(String tableName) throws IOException {
        init();
        TableName tn = TableName.valueOf(tableName);
        if (admin.tableExists(tn)) {
            admin.disableTable(tn);
            admin.deleteTable(tn);
            System.out.println("表:"+tableName+"已成功删除");
        }
        close();
    }
    /**
     * 查看已有表
     * @throws IOException
     */
    public void listTables() throws IOException {
        init();
        HTableDescriptor hTableDescriptors[] = admin.listTables();
        for(HTableDescriptor hTableDescriptor :hTableDescriptors){
            System.out.println(hTableDescriptor.getNameAsString());
        }
        close();
    }
    /**
     * 向某一行的某一列插入数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名(如果其列族下没有子列,此参数可为空)
     * @param val 值
     * @throws IOException
     */
    public void insertRow(String tableName,String rowKey,String colFamily,String col,String val) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes());
        put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes());
        System.out.println("数据插入成功");
        table.put(put);
        table.close();
        close();
    }
 
    /**
     * 删除数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名
     * @throws IOException
     */
    public void deleteRow(String tableName,String rowKey,String colFamily,String col) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(rowKey.getBytes());
        //删除指定列族的所有数据
        //delete.addFamily(colFamily.getBytes());
        //删除指定列的数据
        //delete.addColumn(colFamily.getBytes(), col.getBytes());
 
        table.delete(delete);
        System.out.println("信息已经删除");
        table.close();
        close();
    }
    /**
     * 根据行键rowkey查找数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名
     * @throws IOException
     */
    public void getData(String tableName,String rowKey,String colFamily,String col)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Get get = new Get(rowKey.getBytes());
        get.addColumn(colFamily.getBytes(),col.getBytes());
        Result result = table.get(get);
        showCell(result);
        table.close();
        close();
    }
    /**
     * 格式化输出
     * @param result
     */
    public void showCell(Result result){
        Cell[] cells = result.rawCells();
        for(Cell cell:cells){
            System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
            System.out.println("Timetamp:"+cell.getTimestamp()+" ");
            System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
            System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
        }
    }
}

3、程序关闭

每次操作之后,记得关闭自己的hadoop已经hbase,养成良好的操作习惯!

stop-hbase.sh
stop-dfs.sh
exit

在这里插入图片描述
以上就是本次博客的全部内容啦,希望阅读的小伙伴可以懂得如何通过java代码实现对Hbase数据库的操作,代码不要照搬,理解代码才是硬道理,一定要熟悉后理解哦!
遇到问题的小伙伴记得评论区留言,林君学长看到会为大家解答的,这个学长不太冷!

陈一月的又一天编程岁月^ _ ^

发布了76 篇原创文章 · 获赞 111 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_42451251/article/details/105468854