使用Java操作HBase(增,删,改,查操作)

Posted lambda-小张

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Java操作HBase(增,删,改,查操作)相关的知识,希望对你有一定的参考价值。

目录

在这里我用的是idea操作的

一、配置

1.首先确保HBase集群已经开启

2.配置hosts文件

 3、创建maven项目,在pom.xml文件中添加如下依赖项

4.配置log4j.properties文件

二、连接增删改查

1.连接测试类

 2.创建表

3.添加数据

4.查询指定行键数据

5.查询全表数据

6.查询表的行数

 7.查询已存在表

8.删除指定行数据

9.删除表


在这里我用的是idea操作的

一、配置

1.首先确保HBase集群已经开启

[root@hadoop ~]# jps
2761 HQuorumPeer
2137 ResourceManager
7114 Jps
2858 HMaster
1691 NameNode
1789 DataNode
2237 NodeManager
2943 HRegionServer
1983 SecondaryNameNode

上面所有节点都有

2.配置hosts文件

在你所在电脑配置你的hadoop集群信息,所以需要找到并修改hosts文件:

hosts的目录:C:\\Windows\\System32\\drivers\\etc

在这里我的伪分布式下的,修改hosts文件时需要打开所有权限,才能保存

使用记事本打开,修改后并保存

在文档最后一行加上IP空格主机名

任务管理器中输入ping 主机名

C:\\Users\\>ping hadoop
192.168.171.151 的 Ping 统计信息:
    数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
    最短 = 0ms,最长 = 1ms,平均 = 0ms

 3、创建maven项目,在pom.xml文件中添加如下依赖项

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lenovo</groupId>
    <artifactId>0406</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
<!-- 从这里导入就可以了 -->
    <dependencies>
<dependency>  
     <groupId>jdk.tools</groupId>   
     <artifactId>jdk.tools</artifactId>  
     <version>1.8</version>  
     <scope>system</scope>  
     <systemPath>C:/Program Files/Java/jdk1.8.0_91/lib/tools.jar</systemPath>  
 </dependency> 
  <!-- HBase -->
  
   <dependency>
     <groupId>org.apache.hadoop</groupId>
     <artifactId>hadoop-common</artifactId>
     <version>2.7.3</version>
 </dependency>
  
 <dependency>  
     <groupId>org.apache.hbase</groupId>
     <artifactId>hbase-it</artifactId>
     <version>1.3.1</version>
     <type>pom</type>
 </dependency>
    </dependencies>
<!-- 这里结束 -->
</project>

4.配置log4j.properties文件

将log4j.properties文件拷贝到src/main/resources目录下,这样方便我们看到执行过程

log4j.properties文件路径在hadoop安装包里面:hadoop-2.7.3\\etc\\hadoop\\log4j.properties

二、连接增删改查

1.连接测试类

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.junit.Test;

import java.io.IOException;

    /**
     * @Date 2022.04.20
     * @AUthor lambda-小张
     * @Description 测试连接
     *单元测试
 */
public class Demo 
    @Test
    public void test()
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum","IP地址");
        //获取连接
        try 
            Connection conn = ConnectionFactory.createConnection(con);
            System.out.println(conn);
         catch (IOException e) 
            e.printStackTrace();
        
    


运行结果

 2.创建表

/**
     * @Date 2022.04.20
     * @AUthor lambda-小张
     * @Description 创建表
     * Demo类名
     * demo表名
     */
public static void main(String[] args) 
    new Demo().createTable("demo","userinfo");
    
public void createTable(String tableName, String familyName) 
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        try 
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            //获取表格描述器
            HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf(tableName));
            //添加列簇
            hTableDescriptor.addFamily(new HColumnDescriptor(familyName));
            //执行创建操作
            admin.createTable(hTableDescriptor);
            //关流

            System.out.println("创建成功");
         catch (IOException e) 
            e.printStackTrace();
         finally 
            try 
                admin.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        

    

运行结果:

  

HBase中的结果:

hbase(main):001:0> list
TABLE                                                                                                                                                          
demo                                                                                                                                                                  
1 row(s) in 0.3300 seconds
=> ["demo"]

3.添加数据

  /**
     * @Date 2022.04.20
     * @AUthor lambda-小张
     * @Description 添加数据
     * Demo类名
     * demo表名
     */
public static void main(String[] args) 
        boolean result = new Demo().addOneData("demo", "张三", "753159");//1001的数据
//        boolean result = new Demo().addOneData("demo", "lisi", "752159");//1002的数据
//        boolean result = new Demo().addOneData("demo", "王五", "762159");//1003的数据
        System.out.println(result);
    
public boolean addOneData(String tableName,String userName,String passWord)
        //获取配置对象
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum","IP地址");
        Connection conn = null;
        Table table = null;
        //获取连接
        try 
            conn = ConnectionFactory.createConnection(con);
            //获取表的信息
            table = conn.getTable(TableName.valueOf(tableName));
            //设置行键
            Put put = new Put("1001".getBytes());
            //设置列的标识 以及列值
            put.addColumn("userinfo".getBytes(),"username".getBytes(),userName.getBytes());
            put.addColumn("userinfo".getBytes(),"password".getBytes(),passWord.getBytes());
            //执行添加
            table.put(put);
            //关流
            table.close();
            conn.close();

         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                table.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        
        return true;
    

运行结果:

  

HBase中的结果:

hbase(main):003:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1001                               column=userinfo:name, timestamp=1650476863233, value=\\xE5\\xBC\\xA0\\xE4\\xB8\\x89                        
 1001                               column=userinfo:password, timestamp=1650476863233, value=753159                                      
1 row(s) in 0.0230 seconds

4.查询指定行键数据

  /**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 查询行键数据
     * demo表名
     * 单元测试
     */
@Test
    //获取全部的数据
    public void getAllData2()
        //获取配置对象
        Configuration con= new Configuration();
        con.set("hbase.zookeeper.quorum","ip地址");
        Connection conn = null;
        Table user = null;
        try 
            //获取连接
            conn = ConnectionFactory.createConnection(con);
            user = conn.getTable(TableName.valueOf("demo"));
            //创建get
            Get get = new Get("1001".getBytes());
            //获取所有列
            Result result = user.get(get);
            Cell[] cells = result.rawCells();
            for (Cell cell : cells) 
                //获取行键
                byte[] rowKey = result.getRow();
                String s = new String(rowKey);
                //获取列名
                byte[] qualifier = cell.getQualifier();
                String columnName = new String(qualifier);
                //获取值
                byte[] value = cell.getValue();
                String value2 = new String(value);
                System.out.println("行键:"+s+"列名:"+columnName+"值:"+value2);
            



         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                user.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            

        
    

运行结果:

HBase中的结果:

hbase(main):007:0> get 'demo','1001'
COLUMN                              CELL                                                                                                 
 userinfo:name                      timestamp=1650477242603, value=\\xE7\\x8E\\x8B\\xE4\\xBA\\x94                                              
 userinfo:password                  timestamp=1650477242603, value=762159                                                                
1 row(s) in 0.0780 seconds

5.查询全表数据

 /**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 查询全表数据
     * demo表名
     * 单元测试
     */
@Test
    public void sacnAllData() 
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Table user = null;
        try 
            conn = ConnectionFactory.createConnection(con);
            user = conn.getTable(TableName.valueOf("demo"));
            Scan scan = new Scan();
            scan.setStartRow("1001".getBytes());
            scan.setStopRow("1004".getBytes());//小一位
            ResultScanner scanner = user.getScanner(scan);
            for (Result result : scanner) 
                List<Cell> cells = result.listCells();
                for (Cell cell : cells) 
                    byte[] rowKey = result.getRow();
                    String s = new String(rowKey);
                    byte[] qualifier = cell.getQualifier();
                    String columnName = new String(qualifier);
                    byte[] value = cell.getValue();
                    String value2 = new String(value);
                    System.out.println("行键:" + s + "列名:" + columnName + "值:" + value2);
                
            
         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                user.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        
    

运行结果:

 HBase中的结果:

hbase(main):008:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1001                               column=userinfo:name, timestamp=1650477242603, value=\\xE7\\x8E\\x8B\\xE4\\xBA\\x94                        
 1001                               column=userinfo:password, timestamp=1650477242603, value=762159                                      
 1002                               column=userinfo:name, timestamp=1650477294338, value=lisi                                            
 1002                               column=userinfo:password, timestamp=1650477294338, value=752159                                      
 1003                               column=userinfo:name, timestamp=1650477429031, value=\\xE5\\xBC\\xA0\\xE4\\xB8\\x89                        
 1003                               column=userinfo:password, timestamp=1650477429031, value=753159                                      
3 row(s) in 0.0280 seconds

6.查询表的行数

/**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 查询表的行数
     * demo表名
     * 单元测试
     */
@Test
    public void countRows()
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Table student = null;
        try 
            conn = ConnectionFactory.createConnection(con);
            student = conn.getTable(TableName.valueOf("demo"));
            Scan scan = new Scan();
            ResultScanner scanner = student.getScanner(scan);
            int num = 0;
            for(Result result = scanner.next();result!=null;result=scanner.next()) 
                num++;
            
            System.out.println("行数:"+num);

         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                student.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        


    

运行结果:

  HBase中的结果:

hbase(main):009:0> count 'demo'
3 row(s) in 0.0280 seconds

=> 3

 7.查询已存在表

/**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 查询已存在表
     * demo表名
     * 单元测试
     */
@Test
    public void listTables()
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        try 
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            HTableDescriptor[] hTableDescriptors = admin.listTables();
            for (HTableDescriptor hTableDescriptor : hTableDescriptors) 
                System.out.println(hTableDescriptor.getNameAsString());
            
         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                admin.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        
    

运行结果:

 HBase中的结果:

hbase(main):011:0> list
TABLE                                                                                                                                    
demo                                                                                                                                     
helloWorld                                                                                                                               
student                                                                                                                                  
user                                                                                                                                     
year                                                                                                                                     
5 row(s) in 0.0330 seconds

=> ["demo", "helloWorld", "student", "user", "year"]

8.删除指定行数据

/**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 删除指定行数据
     * demo表名
     * 单元测试
     */
@Test
    public void deleteDataData() 
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "ip地址");
        //获取连接
        Connection conn = null;
        Table helloWorld = null;

        try 
            conn = ConnectionFactory.createConnection(con);
            helloWorld = conn.getTable(TableName.valueOf("demo"));
            Delete delete = new Delete("1001".getBytes());
            helloWorld.delete(delete);
            System.out.println("删除成功");
         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                helloWorld.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        
    

运行结果:

 HBase中的结果:

hbase(main):012:0> scan 'demo'
ROW                                 COLUMN+CELL                                                                                          
 1002                               column=userinfo:name, timestamp=1650477294338, value=lisi                                            
 1002                               column=userinfo:password, timestamp=1650477294338, value=752159                                      
 1003                               column=userinfo:name, timestamp=1650477429031, value=\\xE5\\xBC\\xA0\\xE4\\xB8\\x89                        
 1003                               column=userinfo:password, timestamp=1650477429031, value=753159                                      
2 row(s) in 0.0230 seconds

9.删除表

/**
     * @Date 2022.04.21
     * @AUthor lambda-小张
     * @Description 删除表数据
     * demo表名
     * 单元测试
     */
@Test
    public void deleteTable()
        Configuration con = new Configuration();
        con.set("hbase.zookeeper.quorum", "IP地址");
        //获取连接
        Connection conn = null;
        Admin admin = null;
        Table student = null;

        try 
            conn = ConnectionFactory.createConnection(con);
            //拿到admin
            admin = conn.getAdmin();
            student = conn.getTable(TableName.valueOf("demo"));
            admin.disableTable(TableName.valueOf("demo"));
            admin.deleteTable(TableName.valueOf("demo"));
            System.out.println("删除表成功");
         catch (IOException e) 
            e.printStackTrace();
        finally 
            try 
                student.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                admin.close();
             catch (IOException e) 
                e.printStackTrace();
            
            try 
                conn.close();
             catch (IOException e) 
                e.printStackTrace();
            
        

    

运行结果:

  HBase中的结果:

hbase(main):013:0> list
TABLE                                                                                                                                    
helloWorld                                                                                                                               
student                                                                                                                                  
user                                                                                                                                     
year                                                                                                                                     
4 row(s) in 0.0480 seconds

=> ["helloWorld", "student", "user", "year"]

以上是关于使用Java操作HBase(增,删,改,查操作)的主要内容,如果未能解决你的问题,请参考以下文章

好用的SQL TVP~~独家赠送[增-删-改-查]的例子

JavaScriptDOM操作那些事(增 删 改 查)

Python---MySQL数据库之四大操作(增 删 改 查)

Javascript操作Cookie(增,删,改,查)

数据库: PHP使用PDO连接数据库实现增 删 改 查 操作

微信小程序云开发,数据库“增”“删”“改”“查”操作