数据库实验6Hbase应用开发实验Java开发

一、实验内容与完成情况:(实验具体步骤和实验截图说明)
实验环境:
1、 操作系统:Linux(建议Ubuntu16.04);
2、 Hadoop版本:2.7.1;
3、 JDK版本:1.7或以上版本;
4、 Java IDE:Eclipse。

实验目的:
1、 理解HBase在Hadoop体系结构中的角色;
2、 熟练使用HBase操作常用的Shell命令;
3、 熟悉HBase操作常用的Java API。

实验步骤:

(一)编程实现以下指定功能,并用 Hadoop 提供的 HBase Shell 命令完成相同任务:

1、列出 HBase 所有的表的相关信息,例如表名;
2、在终端打印出指定的表的所有记录数据;
3、向已经创建好的表添加和删除指定的列族或列;
4、清空指定的表的所有记录数据;
5、统计表的行数。

1.列出 HBase 所有的表的相关信息,例如表名

方式:命令+代码+截图
HBase Shell:List
在这里插入图片描述①Java Api (列出 HBase 所有的表的相关信息,例如表名;)

package homework;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;

public class Test_1 {
	public static Configuration configuration;
	public static Connection connection;
	public static Admin admin;

	/**
 	* @param args
	 */
	//建立连接
    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();
        }
    }  

    /**
     * 查看已有表
     * @throws IOException
     */
    public static void listTables() throws IOException {
        init();
        HTableDescriptor hTableDescriptors[] = admin.listTables();
        for(HTableDescriptor hTableDescriptor : hTableDescriptors){
            System.out.println(hTableDescriptor.getNameAsString());
        }
        close();
    }    

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test_1 t =new Test_1();
		try {
			System.out.println("以下为Hbase 数据库中所存的表信息");
			t.listTables();
		} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		}	      
	}
}

截图:在这里插入图片描述

2.在终端打印出指定的表的所有记录数据;

方式:命令+代码+截图
HBase Shell:scan ‘student’
在这里插入图片描述①Java Api (在终端打印出指定的表的所有记录数据;)

package homework; 

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import java.io.IOException;
import java.util.Scanner;

public class Test_2 {
	public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;

	/**
	 * @param args
	 */   
    //建立连接
    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();
        }
    }

    /**
     * 根据表名查找表信息
     */
    public static void getData(String tableName)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);       
        for(Result result:scanner)
        {
         showCell((result));
        }
        close();
    }

    /**
     * 格式化输出
     * @param result
     */
    public static 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("column Name(列名):"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:(值)"+new String(CellUtil.cloneValue(cell))+" ");
            System.out.println();
        }
    }   

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Test_2 t =new Test_2();
		System.out.println("请输入要查看的表名");
		Scanner scan = new Scanner(System.in);
		String tableName=scan.nextLine();
		System.out.println("信息如下:");
		t.getData(tableName);
	}
}

截图:
在这里插入图片描述

2.(向已经创建好的表添加和删除指定的列族或列)

方式:命令+代码+截图
Hbase shell(添加列族):
put ‘student’,‘95003’,‘Sname’,‘wangjinxuan’
在这里插入图片描述
HBase Shell(删除列族):
因为hbase中没有删除shell命令直接删除指定行的列族信息(包括其中的列的信息),所以需要先将所有指定行的列族信息的所有信息,然后使用delete一个一个作删除。

delete ‘student’ ,’95003’,’Sname:123’
delete ‘student’ ,’95003’,’Sname’
student为表名,95003为行键,Sname为列族名,123为列名
在这里插入图片描述
删除整个行记录:
Deleteall ‘student’ ,’95003’
student为表名,95003为行键在这里插入图片描述

Java Api (在终端打印出指定的表的所有记录数据;)

package homework;

import java.io.IOException;
import java.util.Scanner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
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 org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
 
public class Test_3 {
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();
        }
    }    

    /**
     * 向某一行的某一列插入数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名(如果其列族下没有子列,此参数可为空)
     * @param val 值
     * @throws IOException
     */
    public static 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());
        table.put(put);
        table.close();
        close();
    } 

    /**
     * 根据表名查找表信息
     */
    public static void getData(String tableName)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        for(Result result:scanner)
        {
         showCell((result));
        }
        close();
    } 

    /**
     * 格式化输出
     * @param result
     */
    public static 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("column Name(列名):"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:(值)"+new String(CellUtil.cloneValue(cell))+" ");
            System.out.println();
        }
    }

    /**
     * 删除数据
     * @param tableName 表名
     * @param rowKey 行键
     * @param colFamily 列族名
     * @param col 列名
     * @throws IOException
     */
    public static 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());    
        boolean flag2 =true;
        while(flag2){
	        System.out.println("请输入你的选择 1-删除列族的所有数据  2-指定列的数据");
	        Scanner scanner=new Scanner(System.in);
	        String chooseString = scanner.nextLine();
	        switch (chooseString) {
				case "1":
				{
				//删除指定列族的所有数据
				    delete.addFamily(colFamily.getBytes());
				    table.delete(delete);
				    table.close();
				    close();
				    break;
				}
				case "2":
				{
				//删除指定列的数据
					delete.addColumn(colFamily.getBytes(), col.getBytes());
				    table.delete(delete);
				    table.close();
				    close();
				    break;
				}
				default:
				{
					System.out.println("   你的输入有误 !!!    ");
					table.close();
					close();
					break;
				}
			}
			System.out.println(" 你要继续操作吗? 是-true 否-false ");
			flag2=scanner.nextBoolean();
	    }
    }

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test_3 t =new Test_3();
		boolean flag =true;
		while(flag){
			System.out.println("------------向已经创建好的表中添加和删除指定的列簇或列--------------------");
			System.out.println("              请输入您要进行的操作   1- 添加          2-删除                       ");
			Scanner scan = new Scanner(System.in);
			String choose1=scan.nextLine();
			switch (choose1) {
			case "1":{
				System.out.println("请输入要添加的表名");
				String tableName=scan.nextLine();
				System.out.println("请输入要添加的表的行键");
				String rowKey=scan.nextLine();
				System.out.println("请输入要添加的表的列簇");
				String colFamily=scan.nextLine();
				System.out.println("请输入要添加的表的列名");
				String col=scan.nextLine();
				System.out.println("请输入要添加的值");
				String val=scan.nextLine();
				try {
					t.insertRow(tableName, rowKey, colFamily, col, val);
					System.out.println("插入成功:");
					t.getData(tableName);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.getMessage();
				}
				break;
			}
	        case "2":{
			    System.out.println("请输入要删除的表名");
			    String tableName=scan.nextLine();
			    System.out.println("请输入要删除的表的行键");
			    String rowKey=scan.nextLine();
			    System.out.println("请输入要删除的表的列簇");
			    String colFamily=scan.nextLine();
			    System.out.println("请输入要删除的表的列名");
			    String col=scan.nextLine();
			    try {
			        System.out.println("----------------------表的原本信息如下---------------------");
			        t.getData(tableName);
			        System.out.println("____________________________正在执行删除操作........\n");
					t.deleteRow(tableName, rowKey, colFamily, col);
					System.out.println("____________________________删除成功_______________\n");
					System.out.println("---------------------删除后  表的信息如下---------------------");
					t.getData(tableName);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.getMessage();
				}
				break;
	        }
			default:
			{
				System.out.println("   你的操作有误 !!!    ");
				break;
			}
		}
		System.out.println(" 你要继续操作吗? 是-true 否-false ");
		flag=scan.nextBoolean();
	}
	System.out.println("   程序已退出!    ");
	}
}

截图:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
备注:
delete 'student’,’95003’,’Sname’
仅能删除Sname列下的数据,并不能删除Sname列簇下的别的列名的数据,因为它默认删除删除Sname:空下的数据,作字符串相等,并不是包含。暂时依靠两次删除来删除数据。

4、清空指定的表的所有记录数据

方式:命令+代码+截图
Hbase Shell命令:
truncate ‘student’
在这里插入图片描述Java API

package homework;
import java.io.IOException;
import java.util.Scanner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
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 org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class Test_4 {
public static Configuration configuration;
    public static Connection connection;
    public static Admin admin;
	/**
	 * @param args
	 */
    //建立连接
    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();
        }
    }   

    /**
     * 清空制定的表的所有记录数据
     * @param args
     * @throws IOException
     */
    public static void clearRows(String tableName) throws IOException{
	    init();
	    HBaseAdmin admin1=new HBaseAdmin(configuration);
	    HTableDescriptor tDescriptor =admin1.getTableDescriptor(Bytes.toBytes(tableName));//读取了之前表的表名 列簇等信息,然后再进行删除操作。 总思想是先将原表结构保留下来,然后进行删除,再重新依据保存的信息重新创建表。
	    TableName tablename=TableName.valueOf(tableName);
	    //删除表
	    admin.disableTable(tablename);
	    admin.deleteTable(tablename);
	    //重新建表
	    admin.createTable(tDescriptor);
	    close();
    }   

    /**
     * 根据表名查找表信息
     */
    public static void getData(String tableName)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);      
        for(Result result:scanner)
        {
            showCell((result));
        }
        close();
    }  

    /**
     * 格式化输出
     * @param result
     */
    public static 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("column Name(列名):"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:(值)"+new String(CellUtil.cloneValue(cell))+" ");
            System.out.println();
        }
    }

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Test_4 test_4=new Test_4();
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入要清空的表名");
		String tableName=scan.nextLine();
			try {
			System.out.println("表原来的信息:");
			test_4.getData(tableName);
			test_4.clearRows(tableName);
			System.out.println("表已清空:");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

在这里插入图片描述
错误的设计(补充)

public static void clearRows(String tableName) throws IOException{
     init();
     TableName tablename=TableName.valueOf(tableName);
     //删除表
     admin.disableTable(tablename);
     admin.deleteTable(tablename);
     HTableDescriptor tDescriptor =new HTableDescriptor(tableName);//在删除原表前没有读取之前的表的结构信息,直接创建,只有表名,没有一个列簇,所以创建失败。
      admin.createTable(tDescriptor);
      close();
}   

5、统计表的行数。

方式:命令+代码+截图
Hbase shell 命令:
count ‘student’
截图:
在这里插入图片描述
Java API 命令:

package homework;

import java.io.IOException;
import java.util.Scanner;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
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 org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;

public class Test_5 {
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();
        }
    }

    public static void countRows (String tableName) throws IOException{
	    init();
	    Table table = connection.getTable(TableName.valueOf(tableName));
	    Scan scan = new Scan();
	    ResultScanner scanner =table.getScanner(scan);
	    int num = 0;
	    for(Result result = scanner.next();result!=null;result=scanner.next()){
			num++;
	    }
	    System.out.println("行数:"+num);
	    scanner.close();
	    close();
    }

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Test_5 test_5=new Test_5();
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入要统计行数的表名");
		String tableName=scan.nextLine();
		test_5.countRows(tableName);
	}
}

在这里插入图片描述

(二)HBase 数据库操作

现有以下关系型数据库中的表和数据,要求将其转换为适合于 HBase 存储的表并插入数据:
学生表(Student)
在这里插入图片描述
课程表(Course)
在这里插入图片描述
选课表(SC)
在这里插入图片描述

①学生Student表(主键的列名是随机分配的,因此无需创建主键列)
创建表: create ‘Student’,‘S_No’,‘S_Name’,‘S_Sex’,‘S_Age’
在这里插入图片描述
插入数据:插入shell命令
第一行数据
put ‘Student’,‘s001’,‘S_No’,‘2015001’ 
put ‘Student’,‘s001’,‘S_Name’,‘Zhangsan’ 
put ‘Student’,‘s001’,‘S_Sex’,‘male’ 
put ‘Student’,‘s001’,‘S_Age’,‘23’

第二行数据
put ‘Student’,‘s002’,‘S_No’,‘2015002’ 
put ‘Student’,‘s002’,‘S_Name’,‘Mary’ 
put ‘Student’,‘s002’,‘S_Sex’,‘female’ 
put ‘Student’,‘s002’,‘S_Age’,‘22’

第三行数据
put ‘Student’,‘s003’,‘S_No’,‘2015003’ 
put ‘Student’,‘s003’,‘S_Name’,‘Lisi’ 
put ‘Student’,‘s003’,‘S_Sex’,‘male’ 
put ‘Student’,‘s003’,‘S_Age’,‘24’ 
在这里插入图片描述
在这里插入图片描述
添加数据并查看
在这里插入图片描述

添加3个学生
② 课程Course表
创建表:create ‘Course’,‘C_No’,‘C_Name’,‘C_Credit’
在这里插入图片描述
创建Course表:插入shell命令
第一行数据
put ‘Course’,‘c001’,‘C_No’,‘123001’
put ‘Course’,‘c001’,‘C_Name’,‘Math’
put ‘Course’,‘c001’,‘C_Credit’,‘2.0’

第二行数据
put ‘Course’,‘c001’,‘C_No’,‘123002’
put ‘Course’,‘c001’,‘C_Name’,‘Computer Science’
put ‘Course’,‘c001’,‘C_Credit’,‘5.0’

第三行数据
put ‘Course’,‘c001’,‘C_No’,‘123003’
put ‘Course’,‘c001’,‘C_Name’,‘English’
put ‘Course’,‘c001’,‘C_Credit’,‘3.0’

在这里插入图片描述

添加数据
在这里插入图片描述
添加三个课程
③选课表
创建表:create ‘SC’,‘SC_Sno’,‘SC_Cno’,‘SC_Score’
在这里插入图片描述

创建表SC

插入数据:插入shell命令

第一行数据
put ‘SC’,‘sc001’,‘SC_Sno’,‘2015001’
put ‘SC’,‘sc001’,‘SC_Cno’,‘123001’
put ‘SC’,‘sc001’,‘SC_Score’,‘86’

第二行数据
put ‘SC’,‘sc002’,‘SC_Sno’,‘2015001’
put ‘SC’,‘sc002’,‘SC_Cno’,‘123003’
put ‘SC’,‘sc002’,‘SC_Score’,‘69’

第三行数据
put ‘SC’,‘sc003’,‘SC_Sno’,‘2015002’
put ‘SC’,‘sc003’,‘SC_Cno’,‘123002’
put ‘SC’,‘sc003’,‘SC_Score’,‘77’

第四行数据
put ‘SC’,‘sc004’,‘SC_Sno’,‘2015002’
put ‘SC’,‘sc004’,‘SC_Cno’,‘123003’
put ‘SC’,‘sc004’,‘SC_Score’,‘99’

第五行数据
put ‘SC’,‘sc005’,‘SC_Sno’,‘2015003’
put ‘SC’,‘sc005’,‘SC_Cno’,‘123001’
put ‘SC’,‘sc005’,‘SC_Score’,‘98’

第六行数据
put ‘SC’,‘sc006’,‘SC_Sno’,‘2015003’
put ‘SC’,‘sc006’,‘SC_Cno’,‘123002’
put ‘SC’,‘sc006’,‘SC_Score’,‘95’
在这里插入图片描述
插入数据
在这里插入图片描述
数据显示

二、按要求编程。

1.createTable(String tableName, String[] fields)

创建表,参数 tableName 为表的名称,字符串数组 fields 为存储记录各个字段名称的数组。要求当 HBase 已经存在名为 tableName 的表的时候,先删除原有的表,然后再创建新的表。

2.addRecord(String tableName, String row, String[] fields, String[] values)

向表 tableName、行 row(用 S_Name 表示)和字符串数组 fields 指定的单元格中添加对应的数据 values。其中,fields 中每个元素如果对应的列族下还有相应的列限定符的话,用“columnFamily:column”表示。例如,同时向“Math”、“Computer Science”、“English”三列添加成绩时,字符串数组 fields 为{“Score:Math”, ”Score:Computer Science”, ”Score:English”},数组

values 存储这三门课的成绩。

3.scanColumn(String tableName, String column)

浏览表 tableName 某一列的数据,如果某一行记录中该列数据不存在,则返回 null。要求当参数 column 为某一列族名称时,如果底下有若干个列限定符,则要列出每个列限定符代表的列的数据;当参数 column 为某一列具体名称(例如“Score:Math”)时,只需要列出该列的数据。

4.modifyData(String tableName, String row, String column)

修改表 tableName,行 row(可以用学生姓名 S_Name 表示),列 column 指定的单元格的数据。

5.deleteRow(String tableName, String row)

删除表 tableName 中 row 指定的行的记录。

方式:代码+截图

/**
 * @author zcr
 * @date 2019/2/24-10:07
 */
package homework;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
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 org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class Hbase_Apply {

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

   /**
     * 建表。参数tableName为表的名称,字符串数组fields为存储记录各个域名称的数组。
     * 要求当HBase已经存在名为tableName的表时,先删除原有的表,然后再
     * 创建新的表  field:列族
     * @param myTableName 表名
     * @param colFamily 列族名
     * @throws IOException
     */
    public static void createTable(String tableName,String[] fields) throws IOException {
        init();
        TableName tablename = TableName.valueOf(tableName);
        if(admin.tableExists(tablename)){
            System.out.println("表已存在,将执行删除原表,重建新表!");
            admin.disableTable(tablename);
            admin.deleteTable(tablename);//删除原来的表
        }
        HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
        for(String str:fields){
            HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(str);
            hTableDescriptor.addFamily(hColumnDescriptor);
        }
        admin.createTable(hTableDescriptor);
        System.out.println("表已创建成功");
        close();
    }


    /**
     * 向表 tableName、行 row(用 S_Name 表示)和字符串数组 fields 指定的单元格中
     * 添加对应的数据 values。
     * 其中,fields 中每个元素如果对应的列族下还有相应的列限定符的话,
     * 用“columnFamily:column”表示。
     * 例如,同时向“Math”、“Computer Science”、“English”三列添加成绩时,
     * 字符串数组 fields 为{“Score:Math”, ”Score:Computer Science”, ”Score:English”},
     * 数组values 存储这三门课的成绩。
     */
    public static void addRecord(String tableName,String rowKey,String []fields,String [] values) throws IOException {
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        for (int i = 0; i < fields.length; i++) {
            Put put = new Put(rowKey.getBytes());
            String [] cols = fields[i].split(":");
            if(cols.length==1){
            	put.addColumn(cols[0].getBytes(), "".getBytes(), values[i].getBytes());//因为当输入的是单列族,split仅读出一个字符字符串,即cols仅有一个元素
            }else {
            	put.addColumn(cols[0].getBytes(), cols[1].getBytes(), values[i].getBytes());
			}
            table.put(put);
		}
        table.close();
        close();
    }

    /**
     * 根据表名查找表信息
     */
    public static void getData(String tableName)throws  IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        ResultScanner scanner = table.getScanner(scan);
        for(Result result:scanner){
            showCell((result));
        }
        close();
    }

    /**
     * 格式化输出
     * @param result
     */
    public static 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("column Name(列名):"+new String(CellUtil.cloneQualifier(cell))+" ");
            System.out.println("value:(值)"+new String(CellUtil.cloneValue(cell))+" ");
            System.out.println();
        }
    }

    /**
     * 浏览表 tableName 某一列的数据,如果某一行记录中该列数据不存在,则返回 null。
     * 要求当参数 column 为某一列族名称时,如果底下有若干个列限定符,则要列出每个列限定符代表的列的数据;
     * 当参数 column 为某一列具体名称(例如“Score:Math”)时,只需要列出该列的数据。
     * @param tableName
     * @param column
     * @throws IOException
     */
    public static void scanColumn (String tableName,String column) throws IOException{
     	init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Scan scan = new Scan();
        String [] cols = column.split(":");
        if(cols.length==1){
            scan.addFamily(Bytes.toBytes(column));
        }else { 
            scan.addColumn(Bytes.toBytes(cols[0]),Bytes.toBytes(cols[1]));
		}
        ResultScanner scanner = table.getScanner(scan);
        for (Result result = scanner.next(); result !=null;result = scanner.next()) {
			showCell(result);
		}
        table.close();
        close();
    }

    /**
     * 修改表 tableName,行 row(可以用学生姓名 S_Name 表示),列 column 指定的单元格的数据。
     * @throws IOException
     */
    public static void modifyData(String tableName,String rowKey,String column,String value) throws IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Put put = new Put(rowKey.getBytes());
        String [] cols = column.split(":");
        if(cols.length==1){
   	        put.addColumn(column.getBytes(),"".getBytes() , value.getBytes());//qualifier:列族下的列名
        }else {
   	        put.addColumn(cols[0].getBytes(),cols[1].getBytes() , value.getBytes());//qualifier:列族下的列名
	    }
        table.put(put);
        table.close();
        close();
    }

    /**
     * 删除表 tableName 中 row 指定的行的记录。
     * @throws IOException
     */
    public static void deleteRow(String tableName,String rowKey) throws IOException{
        init();
        Table table = connection.getTable(TableName.valueOf(tableName));
        Delete delete = new Delete(rowKey.getBytes());
   		table.delete(delete);
        table.close();
        close();
    }  

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
	// TODO Auto-generated method stub
	     Test_Two test_Two = new Test_Two();
	     boolean flag =true;
		while(flag){
			System.out.println("------------------------------------------------提供以下功能----------------------------------------------");
			System.out.println("                       1- createTable(创建表  ,提供表名、列族名)                                      ");
			System.out.println("                       2-addRecord (向已知表名、行键、列簇的表添加值)                       ");
			System.out.println("                       3- ScanColumn(浏览表     某一列的数据)                                            ");
			System.out.println("                       4- modifyData(修改某表   某行,某一列,指定的单元格的数据)    ");
			System.out.println("                       5- deleteRow(删除 某表   某行的记录)                                                 ");
			System.out.println("------------------------------------------------------------------------------------------------------------------");
			Scanner scan = new Scanner(System.in);
			String choose1=scan.nextLine();
			switch (choose1) {
				case "1":{
					System.out.println("请输入要创建的表名");
					String tableName=scan.nextLine();
					System.out.println("请输入要创建的表的列族个数");
					int Num=scan.nextInt();
					String [] fields = new String[Num];
					System.out.println("请输入要创建的表的列族");
					/* Scanner scanner = new Scanner(System.in);     scanner.next 如不是全局,即会记得上一次输出。相同地址读入值时*/
					for(int i=0;i< fields.length;i++){
						/*BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
						fields[i] = in.readLine();*/
						/*fields[i]=scan.next(); 因为之前没有输入过,所以可以读入新值*/
						scan = new Scanner(System.in);
					    fields[i]=scan.nextLine();
					}
					System.out.println("正在执行创建表的操作");
					test_Two.createTable(tableName,fields);
					break;
				}
				case "2":{
					System.out.println("请输入要添加数据的表名");
					String tableName=scan.nextLine();
					System.out.println("请输入要添加数据的表的行键");
					String rowKey=scan.nextLine();
					System.out.println("请输入要添加数据的表的列的个数");
					int num =scan.nextInt();
					String fields[]=new String[num];
					System.out.println("请输入要添加数据的表的列信息 共"+num+"条信息");
					for(int i=0;i< fields.length;i++){
						BufferedReader in3= new BufferedReader(new InputStreamReader(System.in));
						fields[i] = in3.readLine();
						/*fields[i]=scan.next(); 因为之前没有输入过,所以可以读入新值*/
					}
					System.out.println("请输入要添加的数据信息 共"+num+"条信息");
					String values[]=new String[num];
					for(int i=0;i< values.length;i++){
						BufferedReader in2 = new BufferedReader(new InputStreamReader(System.in));
						values[i] = in2.readLine();
					}
					System.out.println("原表信息");
					test_Two.getData(tableName);
					System.out.println("正在执行向表中添加数据的操作........\n");
					test_Two.addRecord(tableName, rowKey, fields, values);
					System.out.println("\n添加后的表的信息........");
					test_Two.getData(tableName);
					break;
				}
				case "3":{
					System.out.println("请输入要查看数据的表名");
					String tableName=scan.nextLine();
					System.out.println("请输入要查看数据的列名");
					String column=scan.nextLine();
					System.out.println("查看的信息如下:........\n");
					test_Two.scanColumn(tableName, column);
					break;
				}
				case "4":{
					System.out.println("请输入要修改数据的表名");
					String tableName=scan.nextLine();
					System.out.println("请输入要修改数据的表的行键");
					String rowKey=scan.nextLine();
					System.out.println("请输入要修改数据的列名");
					String column=scan.nextLine();
					System.out.println("请输入要修改的数据信息  ");
					String value=scan.nextLine();
					System.out.println("原表信息如下:........\n");
					test_Two.getData(tableName);
					System.out.println("正在执行向表中修改数据的操作........\n");
					test_Two.modifyData(tableName, rowKey, column, value);
					System.out.println("\n修改后的信息如下:........\n");
					test_Two.getData(tableName);
					break;
				}
				case "5":{
					System.out.println("请输入要删除指定行的表名");
					String tableName=scan.nextLine();
					System.out.println("请输入要删除指定行的行键");
					String rowKey=scan.nextLine();
					System.out.println("原表信息如下:........\n");
					test_Two.getData(tableName);
					System.out.println("正在执行向表中删除数据的操作........\n");
					test_Two.deleteRow(tableName, rowKey);
					System.out.println("\n删除后的信息如下:........\n");
					test_Two.getData(tableName);
					break;
				}
				default:{
					System.out.println("   你的操作有误 !!!    ");
					break;
				}
			}
	        System.out.println(" 你要继续操作吗? 是-true 否-false ");
			flag=scan.nextBoolean();
		}
		System.out.println("   程序已退出!    ");
	}
}

截图1

(CreateTable)
在这里插入图片描述
创建表&列族
在这里插入图片描述
查看创建结果

截图2
addRecord(String tableName, String row, String[] fields, String[] values)
在这里插入图片描述
在这里插入图片描述

截图3
scanColumn(String tableName, String column)
参数 column 为某一列族名称时:
在这里插入图片描述
在这里插入图片描述

当参数 column 为某一列具体名称
在这里插入图片描述

截图4

modifyData(String tableName, String row, String column)
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

截图5

deleteRow(String tableName, String row)
在这里插入图片描述
在这里插入图片描述

补充内容:HBase 常用类介绍。
举例说明
1.HBaseAdmin
关系:org.apache.hadoop.hbase.client.HBaseAdmin
作用:提供接口关系HBase 数据库中的表信息
用法:
HBaseAdmin admin = new HBaseAdmin(config);

2.HTableDescriptor
关系:org.apache.hadoop.hbase.HTableDescriptor
作用:HTableDescriptor 类包含了表的名字以及表的列族信息
用法:
HTableDescriptor htd =new HTableDescriptor(tablename);
Htd.addFamily(new HColumnDescriptor(“myFamily”));

个人理解:HBase 关于单元格数据的存取
具体过程
查看表列(单元格中不同版本(不同时间戳)的数据)
因为Hbase某列的VERSIONS是1,就是默认情况下,该列仅会存取一个版本的列数据,当再次插入时,后面的值会覆盖前面的值。使用get或scan得到的都是最新的数据。在Hbase中对同一条数据的修改或插入都只是put操作,最终看到的都是最新的数据,其它的数据在不同的version中保存。

如何显示多个版本的值,修改表的列结构,让Hbase表支持3个VERSIONS的版本列数据,通过设置列簇的版本个数,即列族下面的列也是同样的版本个数存储。

alter ‘Score2’,{NAME = > ‘course’,VERSION=>3}

  1. 再次查看表结构:
    在这里插入图片描述
    插入三条数据(在同一个单元格)
    在这里插入图片描述
    使用get命令来获取这一行的数据,发现只返回了最新的一行数据。
    在这里插入图片描述

获取多行数据的方法:
在这里插入图片描述
查看列族时情况相同:
在这里插入图片描述
获取多行数据的方法:
在这里插入图片描述

HBase增删改查

HBase创建数据

本章将介绍如何在HBase表中创建的数据。要在HBase表中创建的数据,可以下面的命令和方法:

put 命令,
add() - Put类的方法
put() - HTable 类的方法.
作为一个例子,我们将在HBase中创建下表。
在这里插入图片描述
HBase Table
使用put命令,可以插入行到一个表。它的语法如下:

put ’

’,’row1’,’ colfamily:colname’,’’

插入第一行

将第一行的值插入到emp表如下所示。

hbase(main):005:0> put ‘emp’,‘1’,‘personal data:name’,‘raju’
0 row(s) in 0.6600 seconds
hbase(main):006:0> put ‘emp’,‘1’,‘personal data:city’,‘hyderabad’
0 row(s) in 0.0410 seconds
hbase(main):007:0> put ‘emp’,‘1’,‘professional
data:designation’,‘manager’
0 row(s) in 0.0240 seconds
hbase(main):007:0> put ‘emp’,‘1’,‘professional data:salary’,‘50000’
0 row(s) in 0.0240 seconds
以相同的方式使用put命令插入剩余的行。如果插入完成整个表格,会得到下面的输出。

hbase(main):022:0> scan ‘emp’

ROW COLUMN+CELL
1 column=personal data:city, timestamp=1417524216501, value=hyderabad

1 column=personal data:name, timestamp=1417524185058, value=ramu

1 column=professional data:designation, timestamp=1417524232601,

value=manager

1 column=professional data:salary, timestamp=1417524244109, value=50000

2 column=personal data:city, timestamp=1417524574905, value=chennai

2 column=personal data:name, timestamp=1417524556125, value=ravi

2 column=professional data:designation, timestamp=1417524592204,

value=sr:engg

2 column=professional data:salary, timestamp=1417524604221, value=30000

3 column=personal data:city, timestamp=1417524681780, value=delhi

3 column=personal data:name, timestamp=1417524672067, value=rajesh

3 column=professional data:designation, timestamp=1417524693187,

value=jr:engg
3 column=professional data:salary, timestamp=1417524702514,

value=25000

使用Java API插入数据

可以使用Put 类的add()方法将数据插入到HBase。可以使用HTable类的put()方法保存数据。这些类属于org.apache.hadoop.hbase.client包。下面给出的步骤是在一个HBase表创建数据。

第1步:实例化配置类

Configuration类增加了 HBase 配置文件到它的对象。使用HbaseConfiguration类的create()方法,如下图所示的配置对象。

Configuration conf = HbaseConfiguration.create();

第2步:实例化HTable类

有一类名为HTable,在HBase中实现了Table。这个类用于单个HBase表进行通信。在这个类实例接受配置对象和表名作为参数。可以实例HTable类,如下图所示。

HTable hTable = new HTable(conf, tableName);

第3步:实例化Put类

为了将数据插入到HBase表中,需要使用add()方法和变体。这种方法属于Put类,因此实例化Put类。这个类必须要以字符串格式的列名插入数据。可以实例Put类,如下图所示。

Put p = new Put(Bytes.toBytes(“row1”));

第4步:插入数据

Put类的add()方法用于插入数据。它需要代表列族,分别为:列限定符(列名称)3字节阵列,以及要插入的值。使用add()方法将数据插入HBase表如下图所示。

p.add(Bytes.toBytes("coloumn family "), Bytes.toBytes(“column
name”),Bytes.toBytes(“value”));

第5步:保存数据到表中

插入所需的行后,HTable类put实例的put()方法添加,如下所示保存更改。

hTable.put§;

第6步:关闭HTable实例

创建在HBase的表数据之后,使用close()方法,如下所示关闭HTable实例。

hTable.close();

下面给出的是在HBase的表创建数据的完整程序。

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

public class InsertData{

   public static void main(String[] args) throws IOException {

      // Instantiating Configuration class
      Configuration config = HBaseConfiguration.create();

      // Instantiating HTable class
      HTable hTable = new HTable(config, "emp");

      // Instantiating Put class
      // accepts a row name.
      Put p = new Put(Bytes.toBytes("row1")); 

      // adding values using add() method
      // accepts column family name, qualifier/row name ,value
      p.add(Bytes.toBytes("personal"),
      Bytes.toBytes("name"),Bytes.toBytes("raju"));

      p.add(Bytes.toBytes("personal"),
      Bytes.toBytes("city"),Bytes.toBytes("hyderabad"));

      p.add(Bytes.toBytes("professional"),Bytes.toBytes("designation"),
      Bytes.toBytes("manager"));

      p.add(Bytes.toBytes("professional"),Bytes.toBytes("salary"),
      Bytes.toBytes("50000"));
      
      // Saving the put Instance to the HTable.
      hTable.put(p);
      System.out.println("data inserted");
      
      // closing HTable
      hTable.close();
   }
}

编译和执行上述程序如下所示。

$javac InsertData.java
$java InsertData
下面列出的是输出结果:

data inserted

HBase更新数据

可以使用put命令更新现有的单元格值。按照下面的语法,并注明新值,如下图所示。

put ‘table name’,’row ’,‘Column family:column name’,’new value’
新给定值替换现有的值,并更新该行。

示例

假设HBase中有一个表emp拥有下列数据

hbase(main):003:0> scan ‘emp’
ROW COLUMN+CELL
row1 column=personal:name, timestamp=1418051555, value=raju
row1 column=personal:city, timestamp=1418275907, value=Hyderabad
row1 column=professional:designation, timestamp=14180555,value=manager
row1 column=professional:salary, timestamp=1418035791555,value=50000
1 row(s) in 0.0100 seconds
以下命令将更新名为“Raju’员工的城市值为’Delhi’。

hbase(main):002:0> put ‘emp’,‘row1’,‘personal:city’,‘Delhi’
0 row(s) in 0.0400 seconds
更新后的表如下所示,观察这个城市Raju的值已更改为“Delhi”。

hbase(main):003:0> scan ‘emp’
ROW COLUMN+CELL
row1 column=personal:name, timestamp=1418035791555, value=raju
row1 column=personal:city, timestamp=1418274645907, value=Delhi
row1 column=professional:designation, timestamp=141857555,value=manager
row1 column=professional:salary, timestamp=1418039555, value=50000
1 row(s) in 0.0100 seconds

使用Java API更新数据

使用put()方法将特定单元格更新数据。按照下面给出更新表的现有单元格值的步骤。

第1步:实例化Configuration类

Configuration类增加了HBase的配置文件到它的对象。使用HbaseConfiguration类的create()方法,如下图所示的配置对象。

Configuration conf = HbaseConfiguration.create();

第2步:实例化HTable类

有一类叫HTable,实现在HBase中的Table类。此类用于单个HBase的表进行通信。在这个类实例,它接受配置对象和表名作为参数。实例化HTable类,如下图所示。

HTable hTable = new HTable(conf, tableName);

第3步:实例化Put类

要将数据插入到HBase表中,使用add()方法和它的变体。这种方法属于Put类,因此实例化Put类。这个类必须以字符串格式的列名插入数据。可以实例化Put类,如下图所示。

Put p = new Put(Bytes.toBytes(“row1”));

第4步:更新现有的单元格

Put 类的add()方法用于插入数据。它需要表示列族,列限定符(列名称)3字节阵列,并要插入的值。将数据插入HBase表使用add()方法,如下图所示。

p.add(Bytes.toBytes("coloumn family "), Bytes.toBytes(“column
name”),Bytes.toBytes(“value”));
p.add(Bytes.toBytes(“personal”),
Bytes.toBytes(“city”),Bytes.toBytes(“Delih”));

第5步:保存表数据

插入所需的行后,HTable类实例的put()方法添加如下所示保存更改。

hTable.put§;

第6步:关闭HTable实例

创建在HBase的表数据之后,使用close()方法,如下所示关闭HTable实例。

hTable.close();
下面给出的是完整的程序,在一个特定的表更新数据。

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.util.Bytes;

public class UpdateData{

public static void main(String[] args) throws IOException {

      // Instantiating Configuration class
      Configuration config = HBaseConfiguration.create();

      // Instantiating HTable class
      HTable hTable = new HTable(config, "emp");

      // Instantiating Put class
      //accepts a row name
      Put p = new Put(Bytes.toBytes("row1"));

      // Updating a cell value
      p.add(Bytes.toBytes("personal"),
      Bytes.toBytes("city"),Bytes.toBytes("Delih"));

      // Saving the put Instance to the HTable.
      hTable.put(p);
      System.out.println("data Updated");

      // closing HTable
      hTable.close();
   }
}

编译和执行上述程序如下所示。

$javac UpdateData.java
$java UpdateData
下面列出的是输出结果:

data Updated

HBase读取数据

get命令和HTable类的get()方法用于从HBase表中读取数据。使用 get 命令,可以同时获取一行数据。它的语法如下:

get ’

’,’row1’
下面的例子说明如何使用get命令。扫描emp表的第一行。

hbase(main):012:0> get ‘emp’, ‘1’

COLUMN CELL

personal : city timestamp=1417521848375, value=hyderabad

personal : name timestamp=1417521785385, value=ramu

professional: designation timestamp=1417521885277, value=manager

professional: salary timestamp=1417521903862, value=50000

4 row(s) in 0.0270 seconds

读取指定列

下面给出的是语法,使用get方法读取指定列。

hbase>get ‘table name’, ‘rowid’, {COLUMN => ‘column family:column name ’}
下面给出的示例,是用于读取HBase表中的特定列。

hbase(main):015:0> get ‘emp’, ‘row1’, {COLUMN=>‘personal:name’}

COLUMN CELL

personal:name timestamp=1418035791555, value=raju

1 row(s) in 0.0080 seconds

使用Java API读取数据

从一个HBase表中读取数据,要使用HTable类的get()方法。这种方法需要Get类的一个实例。按照下面从HBase表中检索数据给出的步骤。

第1步:实例化Configuration类

Configuration类增加了HBase的配置文件到它的对象。使用HbaseConfiguration类的create()方法,如下图所示的配置对象。

Configuration conf = HbaseConfiguration.create();

第2步:实例化HTable类

有一类叫HTable,实现在HBase中的Table类。此类用于单个HBase的表进行通信。在这个类实例,它接受配置对象和表名作为参数。实例化HTable类,如下图所示。

HTable hTable = new HTable(conf, tableName);

第3步:实例化获得类

可以从HBase表使用HTable类的get()方法检索数据。此方法提取从一个给定的行的单元格。它需要一个 Get 类对象作为参数。创建如下图所示。

Get get = new Get(toBytes(“row1”));

第4步:读取数据

当检索数据,可以通过ID得到一个单列,或得到一组行一组行ID,或者扫描整个表或行的子集。

可以使用Get类的add方法变种检索HBase表中的数据。

从特定的列族获取指定的列,使用下面的方法。

get.addFamily(personal)
要得到一个特定的列族的所有列,使用下面的方法。

get.addColumn(personal, name)

第5步:获取结果

获取结果通过Get类实例的HTable类的get方法。此方法返回Result类对象,其中保存所请求的结果。下面给出的是get()方法的使用。

Result result = table.get(g);

第6步:从Result实例读值

Result 类提供getValue()方法从它的实例读出值。如下图所示,使用它从Result 实例读出值。

byte [] value =
result.getValue(Bytes.toBytes(“personal”),Bytes.toBytes(“name”));
byte [] value1 =
result.getValue(Bytes.toBytes(“personal”),Bytes.toBytes(“city”));
下面给出的是从一个HBase表中读取值的完整程序

i

mport java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;

public class RetriveData{

   public static void main(String[] args) throws IOException, Exception{
   
      // Instantiating Configuration class
      Configuration config = HBaseConfiguration.create();

      // Instantiating HTable class
      HTable table = new HTable(config, "emp");

      // Instantiating Get class
      Get g = new Get(Bytes.toBytes("row1"));

      // Reading the data
      Result result = table.get(g);

      // Reading values from Result class object
      byte [] value = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("name"));

      byte [] value1 = result.getValue(Bytes.toBytes("personal"),Bytes.toBytes("city"));

      // Printing the values
      String name = Bytes.toString(value);
      String city = Bytes.toString(value1);
      
      System.out.println("name: " + name + " city: " + city);
   }
}

编译和执行上述程序如下所示。

$javac RetriveData.java
$java RetriveData
下面列出的是输出:

name: Raju city: Delhi

HBase删除数据

从表删除特定单元格
使用 delete 命令,可以在一个表中删除特定单元格。 delete 命令的语法如下:

delete ‘

’, ‘’, ‘’, ‘

hbase(main):006:0> delete ‘emp’, ‘1’, ‘personal data:city’,
1417521848375
0 row(s) in 0.0060 seconds

删除表的所有单元格

使用“deleteall”命令,可以删除一行中所有单元格。下面给出是 deleteall 命令的语法。

deleteall ‘

’, ‘’,
这里是使用“deleteall”命令删去 emp 表 row1 的所有单元的一个例子。

hbase(main):007:0> deleteall ‘emp’,‘1’
0 row(s) in 0.0240 seconds
使用scan命令验证表。表被删除后的快照如下。

hbase(main):022:0> scan ‘emp’

ROW COLUMN+CELL

2 column=personal data:city, timestamp=1417524574905, value=chennai

2 column=personal data:name, timestamp=1417524556125, value=ravi

2 column=professional data:designation, timestamp=1417524204, value=sr:engg

2 column=professional data:salary, timestamp=1417524604221, value=30000

3 column=personal data:city, timestamp=1417524681780, value=delhi

3 column=personal data:name, timestamp=1417524672067, value=rajesh

3 column=professional data:designation, timestamp=1417523187, value=jr:engg

3 column=professional data:salary, timestamp=1417524702514, value=25000

使用Java API删除数据

可以从使用HTable类的delete()方法删除HBase表数据。按照下面给出从表中删除数据的步骤。

第1步:实例化Configuration类

Configuration类增加了HBase配置文件到它的对象。可以创建使用HbaseConfiguration类的create()方法,如下图所示的Configuration 对象。

Configuration conf = HbaseConfiguration.create();

第2步:实例化HTable类

有一个类叫HTable,实现在HBase中的Table类。此类用于单个HBase的表进行通信。在这个类实例,它接受配置对象和表名作为参数。实例化HTable类,如下图所示。

HTable hTable = new HTable(conf, tableName);

第3步:实例化Delete 类

通过传递将要删除的行的行ID,在字节数组格式实例化Delete类。也可以通过构造时间戳和Rowlock。

Delete delete = new Delete(toBytes(“row1”));

第4步:选择删除数据

可以使用Delete类的delete方法删除数据。这个类有各种删除方法。选择使用这些方法来删除列或列族。这里显示Delete类方法的用法在下面的例子。

delete.deleteColumn(Bytes.toBytes(“personal”), Bytes.toBytes(“name”));
delete.deleteFamily(Bytes.toBytes(“professional”));

第5步:删除数据

通过HTable类实例的delete()方法,如下所示删除所选数据。

table.delete(delete);

第6步:关闭HTable实例

删除数据后,关闭HTable实例。

table.close();
下面给出的是从HBase表中删除的数据的完整程序。

import java.io.IOException;

import org.apache.hadoop.conf.Configuration;

import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.util.Bytes;

public class DeleteData {

   public static void main(String[] args) throws IOException {

      // Instantiating Configuration class
      Configuration conf = HBaseConfiguration.create();

      // Instantiating HTable class
      HTable table = new HTable(conf, "employee");

      // Instantiating Delete class
      Delete delete = new Delete(Bytes.toBytes("row1"));
      delete.deleteColumn(Bytes.toBytes("personal"), Bytes.toBytes("name"));
      delete.deleteFamily(Bytes.toBytes("professional"));

      // deleting the data
      table.delete(delete);

      // closing the HTable object
      table.close();
      System.out.println("data deleted.....");
   }
}

编译和执行上述程序如下所示。

$javac Deletedata.java
$java DeleteData
下面列出的是输出:

data deleted

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值