java操作hbase的增删改查

2023-05-16

首先需要将hbase安装目录下lib文件夹中的jar文件全部加入到项目类路径下,另外还需要将hadoop相关jar包也加入。

这里需要用到的主要API介绍一下。

Configuration:HBase参数配置对象。

Connection:HBase连接对象,通过ConnectionFactory工厂方法创建,需要传入一个参数配置对象。

Admin:通过Admin实现创建表,删除表操作。

TableName:取代字符串形式的tableName。

Table:使用Table可以新增数据put(),查询数据getScanner()。

下面通过代码来演示如何做常规的操作:

1、初始化配置,构建一个HBase连接器对象。

private static Connection connection;

static{
	Configuration config = HBaseConfiguration.create();
	config.set("hbase.rootdir", "hdfs://server:9000/hbase");
	config.set("hbase.zookeeper.quorum", "server:2181");
	try {
		connection = ConnectionFactory.createConnection(config);
	} catch (IOException e) {
		e.printStackTrace();
	}	
}

2、建表。

public static boolean createTable(String tableName,String columnFamily){
	boolean success = false;
	Admin admin = null;
	TableName tn = TableName.valueOf(tableName);
	try {
		admin = connection.getAdmin();
		if(!admin.tableExists(tn)){
			HTableDescriptor desc = new HTableDescriptor(tn);
			desc.addFamily(new HColumnDescriptor(columnFamily.getBytes()));
			admin.createTable(desc);
			System.out.println("table ["+tableName+"] create ok.");
			success = true;			
		}else{
			System.out.println("table ["+tableName+"] already exists.");
			success = false ;
		}
	} catch (Exception e) {
		success = false ;
	}
	return success;
}

3、插入数据。

public static boolean putData(String tableName,String rowKey,String columnFamily,String qualifier,Object value){
	boolean success = false;
	Admin admin = null;
	TableName table = TableName.valueOf(tableName);
	try {
		admin = connection.getAdmin();
		if(admin.tableExists(table)){
			Table t = connection.getTable(table);
			Put put = new Put(rowKey.getBytes());
			put.addColumn(columnFamily.getBytes(), qualifier.getBytes(), value.toString().getBytes());
			t.put(put);
			success = true;
		}else{
			System.out.println("table ["+tableName+"] does not exist.");
			success = false;
		}
	} catch (Exception e) {
		success = false;
	}
	return success;
}

4、查看数据。 

@SuppressWarnings("deprecation")
public static void getValueByTable(String tableName){
	TableName tn = TableName.valueOf(tableName.getBytes());
	try{
		Table table = connection.getTable(tn);
		ResultScanner rs = table.getScanner(new Scan());
		for(Result r:rs){
			System.out.println("row:"+new String(r.getRow()));
			for(KeyValue kv:r.raw()){
				System.out.println("column family:"+new String(kv.getFamilyArray())
				+" qualifier "+new String(kv.getQualifierArray())
				+" value "+new String(kv.getValueArray()));
			}
		}
	}catch(Exception e){
		e.printStackTrace();
	}
}

5、删除表。

public static boolean dropTable(String tableName){
	boolean success = false;
	Admin admin = null;
	try {
		admin = connection.getAdmin();
		TableName table = TableName.valueOf(tableName);
		if(admin.tableExists(table)){
			admin.disableTable(table);
			admin.deleteTable(table);
			success = true;
		}
	} catch (Exception e) {
		success = false;
	}finally{
		IOUtils.closeQuietly(admin);
	}
	return success;
}

6、以上几段代码展示了,如何初始化hbase连接,创建表,添加数据,查看数据,删除表的操作,下面通过运行,查看效果。这里代码在windows的eclipse ide编码的,为了演示,我们通过ant构建插件sshexec来将代码直接提交到hbase服务器上运行。这里给出完整的构建脚本build.xml。

<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." name="hbase" default="sshexec">
    <property name="main.class" value="com.xxx.hbase.test.HBaseTest"/>
    <property name="src.dir" value="${basedir}/src" />
    <property name="java.lib.dir" value="${basedir}/lib"/>
    <property name="localpath.dir" value="${basedir}"/>
    <property name="dest.dir" value="${basedir}/dest"/>
    <property name="classes.dir" value="${basedir}/classes"/>
    <property name="third.lib.dir" value="${basedir}/lib"/>
    <property name="remote.host" value="10.119.9.149"/>
    <property name="remote.username" value="root"/>
    <property name="remote.password" value="root"/>
    <property name="remote.home" value="~"/>
    
    <path id="compile.classpath">
        <fileset dir="${java.lib.dir}">          
            <include name="tools.jar"/>
        </fileset>
        <fileset dir="${third.lib.dir}">          
            <include name="*.jar"/>
        </fileset>
    </path>
    
    <path id="run.classpath">
        <path refid="compile.classpath"/>
        <pathelement location="${classes.dir}" />
    </path>
    
    <target name="clean">
        <delete dir="${classes.dir}"/>
        <delete dir="${dest.dir}"/>
        <echo level="info">清理完毕</echo>
    </target>
    <target name="init" depends="clean">
        <mkdir dir="${classes.dir}"/>
        <mkdir dir="${dest.dir}"/>
    </target>
    
    <target name="compile" depends="init">
        <javac srcdir="${src.dir}" destdir="${classes.dir}" source="1.8" target="1.8"
        includeAntRuntime="false" debug="false" verbose="false" encoding="UTF-8">
            <classpath refid="compile.classpath"/>
        </javac>   
    </target>
    
    <target name="build" depends="compile">
        <jar jarfile="${dest.dir}/hbasetest.jar">
            <fileset dir="${classes.dir}" includes="**/*.*"/>
        </jar>
    </target>
    
    <target name="ssh" depends="build">
        <scp  file="${dest.dir}/hbasetest.jar" 
         todir="${remote.username}@${remote.host}:${remote.home}" 
         password="${remote.password}" trust="true"/>    
    </target>
    
    <target name="sshexec" depends="ssh">
        <sshexec host="${remote.host}" username="${remote.username}" 
           password="${remote.password}" trust="true" 
           command="hadoop jar ${remote.home}/hbasetest.jar ${main.class}"/>     
    </target>
</project>

7、先运行创建表的任务。

运行截图:

生成表:

 

8、再运行添加数据方法:

 

运行构建成功截图:

 

验证数据是否添加:

9、运行查看数据:

构建结果:

10、删除表,调用删除表api之前,需要先调用禁用表api方法。

构建截图:

验证是否删除:

最后,附上完整的java代码部分:

package com.xxx.hbase.test;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
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.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 HBaseTest {
	
	private static Connection connection;

	static{
		Configuration config = HBaseConfiguration.create();
		config.set("hbase.rootdir", "hdfs://server:9000/hbase");
		config.set("hbase.zookeeper.quorum", "server:2181");
		try {
			connection = ConnectionFactory.createConnection(config);
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	public static boolean createTable(String tableName,String columnFamily){
		boolean success = false;
		Admin admin = null;
		TableName tn = TableName.valueOf(tableName);
		try {
			admin = connection.getAdmin();
			if(!admin.tableExists(tn)){
				HTableDescriptor desc = new HTableDescriptor(tn);
				desc.addFamily(new HColumnDescriptor(columnFamily.getBytes()));
				admin.createTable(desc);
				System.out.println("table ["+tableName+"] create ok.");
				success = true;			
			}else{
				System.out.println("table ["+tableName+"] already exists.");
				success = false ;
			}
		} catch (Exception e) {
			success = false ;
		}
		return success;
	}
	
	public static boolean dropTable(String tableName){
		boolean success = false;
		Admin admin = null;
		try {
			admin = connection.getAdmin();
			TableName table = TableName.valueOf(tableName);
			if(admin.tableExists(table)){
				admin.disableTable(table);
				admin.deleteTable(table);
				success = true;
			}
		} catch (Exception e) {
			success = false;
		}finally{
			IOUtils.closeQuietly(admin);
		}
		return success;
	}
	
	public static boolean putData(String tableName,String rowKey,
        String columnFamily,String qualifier,Object value){
		boolean success = false;
		Admin admin = null;
		TableName table = TableName.valueOf(tableName);
		try {
			admin = connection.getAdmin();
			if(admin.tableExists(table)){
				Table t = connection.getTable(table);
				Put put = new Put(rowKey.getBytes());
				put.addColumn(columnFamily.getBytes(), 
                 qualifier.getBytes(), value.toString().getBytes());
				t.put(put);
				success = true;
			}else{
				System.out.println("table ["+tableName+"] does not exist.");
				success = false;
			}
		} catch (Exception e) {
			success = false;
		}
		return success;
	}
	
	@SuppressWarnings("deprecation")
	public static void getValueByTable(String tableName){
		TableName tn = TableName.valueOf(tableName.getBytes());
		try{
			Table table = connection.getTable(tn);
			ResultScanner rs = table.getScanner(new Scan());
			for(Result r:rs){
				System.out.println("row:"+new String(r.getRow()));
				for(KeyValue kv:r.raw()){
					System.out.println("column family:"
                    +new String(kv.getFamilyArray())
					+" qualifier "+new String(kv.getQualifierArray())
					+" value "+new String(kv.getValueArray()));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws Exception{
		//createTable("stu", "info");
		//putData("stu", "1", "info", "id",1);
		//putData("stu", "1", "info", "name","xxx");
		//getValueByTable("stu");
		dropTable("stu");
	}
	
}

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java操作hbase的增删改查 的相关文章

  • mac系统pip安装package路径问题

    默认情况下 xff0c 通过pip安装会提示Permission Denied 这时候通过sudo pip install xxx可以安装 xff0c 但是安装的路径不是系统默认的路径 xff0c 再次通过pip list列出已经安装过的工
  • xcrun: error: invalid active developer path解决办法

    mac下如果安装过xcode 之后又卸载 xff0c 再使用git等命令时就提示错误 invalid active path Applications Xcode app Contents Developer 一般情况可以通过xcode s
  • Hue安装与配置

    Hue是cloudera提供的hadoop ui 利用它可以很直观的操作和查看hadoop生态应用 一般安装cloudera manager之后会自动带有hue管理界面 xff0c 通过http hueserver 8888即可访问 另外
  • aapt查看apk应用信息

    aapt是Android asset package tools 利用aapt命令可以很方便的查看app包信息 linux下安装配置aapt 先下载aapt 然后放入 usr bin目录 xff0c 并改变权限为可执行文件 aapt帮助 以
  • Git-TortoiseGit使用报错:cannot spawn xxx\bin\ssh.exe: No such file or directory fatal

    一般开发都是用eclipse自带的git插件提交代码 xff0c 今天试了一把TortoiseGit的提交 结果报错 查看TortoiseGit gt Settings xff1a 发现这里环境变量和设置的环境变量不一致 xff0c 猜测是
  • windows+spark本地运行环境搭建

    spark作为一个内存mapreduce框架 xff0c 速度是hadoop的10倍甚至100倍 windows下可以通过简单设置 xff0c 搭建本地运行环境 1 下载spark预编译版本 xff0c spark运行环境依赖jdk sca
  • git clone 报错:Peer reports incompatible or unsupported protocol version解决办法

    git通过git clone下载github上的资源到机器上 xff0c 结果出现如题所示的错误 root 64 server data git clone https github com pingcap tidb docker comp
  • explian使用介绍

    1 xff09 id列数字越大越先执行 xff0c 如果说数字一样大 xff0c 那么就从上往下依次执行 xff0c id列为null的就表是这是一个结果集 xff0c 不需要使用它来进行查询 2 xff09 select type列常见的
  • centos7安装rustup

    rust安装 xff0c 因为被墙的原因 xff0c 在国内几乎很难安装 xff0c 需要通过代理安装 但是rustup却很容易 xff0c 一般在linux下 xff0c 通过官方指定的下列语句 xff0c 基本可以安装rustup cu
  • TiDB在Centos7上通过源码编译安装

    这里难以编译安装的是tikv tidb的三大部分tidb pd tikv中tidb pd均是采用go语言编写 xff0c 安装go语言包即可编译 xff0c 唯独tikv是采用rust语言写的 xff0c 他的编译是最复杂的 而且编译环境非
  • Cloudera Manager 5.12.0图文详解安装过程

    这里介绍的是cdh5的离线安装方式 xff0c 需要的文件提前准备好 xff0c 安装过程会快一些 安装前提 xff1a 机器配置内存一定要高 xff0c 我这里安装的虚拟机均是redhat7 xff1a 内存分别是6G 4G 4G 准备的
  • Failed to get D-Bus connection: Operation not permitted

    docker容器centos7中 xff0c 通过systemctl start service出现下错误 Failed to get D Bus connection Operation not permitted docker中的容器启
  • C++中如何求数组长度

    C 43 43 中没有直接提供求数组长度的方法 xff0c 提供了sizeof begin end 等方法 xff0c 可以供求数组长度使用 可以通过两种方式来求数组长度 xff0c 这里使用模版类 一个是使用sizeof 做除法 xff0
  • IDEA+scala插件开发spark程序

    spark由scala语言编写 xff0c 开发spark程序 xff0c 自然也少不了scala环境 xff0c 这里介绍如何利用Intellij IDEA开发spark 1 环境准备 jdk scala idea这些对于本文来说都已经默
  • hadoop-3.0.1源码编译需要注意的事项

    这次尝试了一下源码编译最新的hadoop3 0 1 xff0c 发现了几个和原来不太一样的地方 记录下来 xff1a 1 需要的jdk不再是原来的1 7 xff0c 直接jdk1 8就编译通过了 xff1b 2 以前安装需要安装编译依赖cm
  • hadoop-3.0.1单节点安装部署

    hadoop 3 0 1编译上和原来有不同的地方 xff0c 部署时 xff0c 也有一些需要注意的地方 安装部署过程一笔带过 xff1a a 设置免秘钥登录 b 设置jdk环境变量 c 配置编译好的hadoop环境变量 xff0c HAD
  • Dll动态链接库创建与隐式链接方式使用

    C 43 43 动态链接库的背景 xff1a windows操作系统诞生以来 xff0c dll就作为win操作系统的基础 xff0c 通常情况下dll不能直接运行 xff0c 也无法接收消息 xff0c 只能供其他可执行程序或者dll来调
  • def模块定义方式创建动态链接库与动态加载使用dll

    前面介绍了通过宏定义 declspec dllexport 的方式创建动态链接库 xff0c 需要定义头文件和宏 xff0c 定义函数时需要使用宏定义 xff0c 这种方式过于繁琐 xff0c 这里介绍使用模块定义文件的方式创建动态链接库
  • Echarts-图表根据值的不同展示成不同的颜色

    series name 39 直接访问 39 type 39 bar 39 barWidth 39 60 39 data 10 52 200 334 390 330 220 itemStyle normal color function p
  • error: no default toolchain configured

    当我们在windows上通过msi方式安装过rust之后 xff0c 运行rustc或者cargo命令行命令时 xff0c 出现如题所示的错误 stackoverflow上有一个issue 说过这个问题 最后的解决办法是通过rustup命令

随机推荐