关于HBase环境搭建和HBase的原理架构,请见笔者相关博客。

1.HBase对java有着较优秀的支持,本文将介绍如何使用java操作Hbase。

首先是pom依赖:

<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-client</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-server</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.hbase</groupId>
<artifactId>hbase-common</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.操作HBase的关键类:

public class HbaseDemo {

private static Admin admin;

public static void main(String[] args){
try {
createTable("user_table", new String[] { "information", "contact" });
User user = new User("001", "xiaoming", "123456", "man", "20", "13355550021", "1232821@csdn.com");
insertData("user_table", user);
User user2 = new User("002", "xiaohong", "654321", "female", "18", "18757912212", "214214@csdn.com");
insertData("user_table", user2);
List<User> list = getAllData("user_table");
System.out.println("--------------------插入两条数据后--------------------");
for (User user3 : list){
System.out.println(user3.toString());
}
System.out.println("--------------------获取原始数据-----------------------");
getNoDealData("user_table");
System.out.println("--------------------根据rowKey查询--------------------");
User user4 = getDataByRowKey("user_table", "user-001");
System.out.println(user4.toString());
System.out.println("--------------------获取指定单条数据-------------------");
String user_phone = getCellData("user_table", "user-001", "contact", "phone");
System.out.println(user_phone);
User user5 = new User("test-003", "xiaoguang", "789012", "man", "22", "12312132214", "856832@csdn.com");
insertData("user_table", user5);
List<User> list2 = getAllData("user_table");
System.out.println("--------------------插入测试数据后--------------------");
for (User user6 : list2){
System.out.println(user6.toString());
}
deleteByRowKey("user_table", "user-test-003");
List<User> list3 = getAllData("user_table");
System.out.println("--------------------删除测试数据后--------------------");
for (User user7 : list3){
System.out.println(user7.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}

//连接集群
public static Connection initHbase() throws IOException {

Configuration configuration = HBaseConfiguration.create();
configuration.set("hbase.zookeeper.property.clientPort", "2181");
configuration.set("hbase.zookeeper.quorum", "127.0.0.1");
//集群配置↓
//configuration.set("hbase.zookeeper.quorum", "101.236.39.141,101.236.46.114,101.236.46.113");
configuration.set("hbase.master", "127.0.0.1:60000");
Connection connection = ConnectionFactory.createConnection(configuration);
return connection;
}

//创建表
public static void createTable(String tableNmae, String[] cols) throws IOException {

TableName tableName = TableName.valueOf(tableNmae);
admin = initHbase().getAdmin();
if (admin.tableExists(tableName)) {
System.out.println("表已存在!");
} else {
HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
for (String col : cols) {
HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(col);
hTableDescriptor.addFamily(hColumnDescriptor);
}
admin.createTable(hTableDescriptor);
}
}

//插入数据
public static void insertData(String tableName, User user) throws IOException {
TableName tablename = TableName.valueOf(tableName);
Put put = new Put(("user-" + user.getId()).getBytes());
//参数:1.列族名 2.列名 3.值
put.addColumn("information".getBytes(), "username".getBytes(), user.getUsername().getBytes()) ;
put.addColumn("information".getBytes(), "age".getBytes(), user.getAge().getBytes()) ;
put.addColumn("information".getBytes(), "gender".getBytes(), user.getGender().getBytes()) ;
put.addColumn("contact".getBytes(), "phone".getBytes(), user.getPhone().getBytes());
put.addColumn("contact".getBytes(), "email".getBytes(), user.getEmail().getBytes());
//HTable table = new HTable(initHbase().getConfiguration(),tablename);已弃用
Table table = initHbase().getTable(tablename);
table.put(put);
}

//获取原始数据
public static void getNoDealData(String tableName){
try {
Table table= initHbase().getTable(TableName.valueOf(tableName));
Scan scan = new Scan();
ResultScanner resutScanner = table.getScanner(scan);
for(Result result: resutScanner){
System.out.println("scan: " + result);
}
} catch (IOException e) {
e.printStackTrace();
}
}

//根据rowKey进行查询
public static User getDataByRowKey(String tableName, String rowKey) throws IOException {

Table table = initHbase().getTable(TableName.valueOf(tableName));
Get get = new Get(rowKey.getBytes());
User user = new User();
user.setId(rowKey);
//先判断是否有此条数据
if(!get.isCheckExistenceOnly()){
Result result = table.get(get);
for (Cell cell : result.rawCells()){
String colName = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
}
return user;
}

//查询指定单cell内容
public static String getCellData(String tableName, String rowKey, String family, String col){

try {
Table table = initHbase().getTable(TableName.valueOf(tableName));
String result = null;
Get get = new Get(rowKey.getBytes());
if(!get.isCheckExistenceOnly()){
get.addColumn(Bytes.toBytes(family),Bytes.toBytes(col));
Result res = table.get(get);
byte[] resByte = res.getValue(Bytes.toBytes(family), Bytes.toBytes(col));
return result = Bytes.toString(resByte);
}else{
return result = "查询结果不存在";
}
} catch (IOException e) {
e.printStackTrace();
}
return "出现异常";
}

//查询指定表名中所有的数据
public static List<User> getAllData(String tableName){

Table table = null;
List<User> list = new ArrayList<User>();
try {
table = initHbase().getTable(TableName.valueOf(tableName));
ResultScanner results = table.getScanner(new Scan());
User user = null;
for (Result result : results){
String id = new String(result.getRow());
System.out.println("用户名:" + new String(result.getRow()));
user = new User();
for(Cell cell : result.rawCells()){
String row = Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
//String family = Bytes.toString(cell.getFamilyArray(),cell.getFamilyOffset(),cell.getFamilyLength());
String colName = Bytes.toString(cell.getQualifierArray(),cell.getQualifierOffset(),cell.getQualifierLength());
String value = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
user.setId(row);
if(colName.equals("username")){
user.setUsername(value);
}
if(colName.equals("age")){
user.setAge(value);
}
if (colName.equals("gender")){
user.setGender(value);
}
if (colName.equals("phone")){
user.setPhone(value);
}
if (colName.equals("email")){
user.setEmail(value);
}
}
list.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
return list;
}

//删除指定cell数据
public static void deleteByRowKey(String tableName, String rowKey) throws IOException {

Table table = initHbase().getTable(TableName.valueOf(tableName));
Delete delete = new Delete(Bytes.toBytes(rowKey));
//删除指定列
//delete.addColumns(Bytes.toBytes("contact"), Bytes.toBytes("email"));
table.delete(delete);
}

//删除表
public static void deleteTable(String tableName){

try {
TableName tablename = TableName.valueOf(tableName);
admin = initHbase().getAdmin();
admin.disableTable(tablename);
admin.deleteTable(tablename);
} catch (IOException e) {
e.printStackTrace();
}
}

}
3.本文以操作User实例为例,新手看下User类:

public class User {

private String id;
private String username;
private String password;
private String gender;
private String age;
private String phone;
private String email;

public User(String id, String username, String password, String gender, String age, String phone, String email) {
this.id = id;
this.username = username;
this.password = password;
this.gender = gender;
this.age = age;
this.phone = phone;
this.email = email;
}

public User(){

}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getGender() {
return gender;
}

public void setGender(String gender) {
this.gender = gender;
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

@Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", gender='" + gender + '\'' +
", age='" + age + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
'}';
}
}
4.测试结果如下图:

java操作HBase成功
---------------------
作者:亦心_yan
原文:https://blog.csdn.net/m0_38075425/article/details/81287836

转载于:https://www.cnblogs.com/leon0/p/11130499.html

HBase的java操作,最新API。(查询指定行、列、插入数据等)相关推荐

  1. java hbase 例子,java操作hbase例子

    java操作hbase例子 java操作hbase,在eclipse中创建一个java项目,将hbase安装文件根目录的jar包和lib目录下jar包导入项目,然后就可以编写java代码操作hbase ...

  2. 数据库查询指定行的数据

    各种不同数据库查询前几行/后几行的sql语句 SqlServer select top 10 * from tablename; Informix select first 10 * from tab ...

  3. sqllite查询数据量_Sqlite3查询指定行数数据

    Sqlite中提供的方法和Mysql的一样,也是通过关键字limit限制. SQL1 selectt.user_id,random()asRandomfromudb_user t limit 10; ...

  4. SQL常用语句-查询指定行的数据

    0实现原理: 根据需要对查询结果进行排序,设定开始查询的位置和查询结果条数,从而达到查询指定行数范围的目的. 1适用场景: 0.查询数据表中指定行数范围的数据 1.需要查询表中第3条到第9条的数据 2 ...

  5. python pandas读取csv文件指定行_python pandas获取csv指定行 列的操作方法

    python pandas获取csv指定行 列的操作方法 pandas获取csv指定行,列 house_info = pd.read_csv('house_info.csv') 1:取行的操作: ho ...

  6. python对csv数据提取某列的某些行_python pandas获取csv指定行 列的操作方法

    pandas获取csv指定行,列 house_info = pd.read_csv('house_info.csv') 1:取行的操作: house_info.loc[3:6]类似于python的切片 ...

  7. numpy使用[]语法索引二维numpy数组中指定指定行之后所有数据行的数值内容(accessing rows in numpy array after specifc row)

    numpy使用[]语法索引二维numpy数组中指定指定行之后所有数据行的数值内容(accessing rows in numpy array after specifc row) 目录

  8. numpy使用[]语法索引二维numpy数组中指定指定行之前所有数据行的数值内容(accessing rows in numpy array before specifc row)

    numpy使用[]语法索引二维numpy数组中指定指定行之前所有数据行的数值内容(accessing rows in numpy array before specifc row) 目录

  9. 基于py3和pymysql的数据库查询,查询某几列的数据

    #python3 #xiaodeng #基于py3和pymysql的数据库查询,查询某几列的数据import pymysql conn=pymysql.connect(....) cur=conn.c ...

  10. easyexcel 读取指定行数据_Excel怎么设置只提取指定行中的数据?

    Excel怎么设置只提取指定行中的数据?有些时候我们需要从一个excel文件中的数据库中提取指定的行或列中的数据.例如如图示,是国内所有上市公司的行业统计.但是现在我们只需要其中部分上市公司的行业统计 ...

最新文章

  1. .NET Core 2.0 Preview 2为开发人员带来改进
  2. GPU 加速下的图像视觉
  3. 【转】MB51搜索字段的设置
  4. python3字符串转数字_Python3基础语法和基本数据类型
  5. JavaScript前端俄罗斯方块小游戏
  6. larval 操作mysql数据库_laravel的数据库操作(三种)
  7. 数论基础 欧几里得
  8. 分享几个超好用的矢量图标网站
  9. matlab 平滑曲线连接_MATLAB数字图像处理-识别广告牌上的文字
  10. oppo enco free2 固件降级工具 (仅供测试使用)
  11. java 裁剪 pdf_PDFBox:使用Java轻松从PDF文件提取内容
  12. 基金与私募基金概念解析:共同基金、单位信托、投资信托计划、券商集合理财、基金专户理财
  13. 一元三次方程求解(求根) - 盛金公式法
  14. 飞猪官方揭秘双11爆款产品打造攻略:1个数据银行+5大设计方法论
  15. 百度地图迁徙大数据_百度地图迁徙大数据:北上广深城内出行年后首次大幅增长...
  16. python3怎么将函数的用法通过help导出到文件
  17. NFA转变为DFA的子集构造法
  18. 数据库sql课后总结
  19. c语言子菜单退出返回主菜单,毕业论文_图书管理系统设计报告077喜欢就下吧(范文1)...
  20. d3.js——箭头的绘制

热门文章

  1. easyexcel 日期类型 convert_Excel个人笔记(数据类型)
  2. 系统学习深度学习(二十八)--DSD
  3. error: src refspec main does not match any
  4. Windows核心编程_调用控制台窗口
  5. 【转】契约测试的必要性
  6. 如何在分组报表中实现组内数据补空行及组内页码
  7. 对话苹果公司的一号员工Bill Fernandez
  8. 在eclipse如何删除无效的maven build
  9. CentOS 6.5 + Nginx 1.8.0 + PHP 5.6(with PHP-FPM) 负载均衡源码安装 之 (三)Nginx负载均衡配置...
  10. java8: hashmap性能提升