HBase Java Api
一、使用Java API操作HBase
1.导包
hadoop-common 2.6.0-cdh
2.写程序
(1)创建一个表DDL
public class HBaseClientDemo{
//创建一个表DDL
@Test
public void createTable()
//1.获取HBase连接配置
HBaseConfiguration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper","nodefour");
conf.set("hbase.zookeeper.property.clientPort","2181");
//2.创建连接
Connection conn=ConnectionFactory.createConnection(conf);
//3.创建admin
Admin admin=conn.getAdmin();
//4.创建表的相关信息,表名
HTableDescriptor student=new HTableDescriptor(TableName.valueOf("student"));
//5.添加列族信息
student.addFamily(new HColumnDescriptor("info"));
student.addFamily(new HColumnDescriptor("score"));
//6.调用创建表的方法进行建表操作
admin.create(student);
//7.关闭连接
conn.close();
)
}
(2)添加数据DML
//添加数据DML
@Test
public void putData2Table()()
//1.获取HBase连接配置
HBaseConfiguration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper","nodefour");
conf.set("hbase.zookeeper.property.clientPort","2181");
//2.创建连接
Connection conn=ConnectionFactory.createConnection(conf);
//3.获取table
Table student=conn.getTable(TableName.valueOf("student"));
//4.向表中添加数据rowkey
Put put=new Put(Bytes.toBytes("1001"));
//5.添加列info:name zhangsan
put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan"));
put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("gender"),Bytes.toBytes("male"));
put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes("11"));
//6.插入数据
student.put(put);
//7.关闭连接
conn.close();
)
扫描以查看数据
scan 'student'
(3)读取数据
//读取数据
@Test
public void getDataFromTable()()
//1.获取HBase连接配置
HBaseConfiguration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper","nodefour");
conf.set("hbase.zookeeper.property.clientPort","2181");
//2.创建连接
Connection conn=ConnectionFactory.createConnection(conf);
//3.获取table
Table student=conn.getTable(TableName.valueOf("student"));
//4.向表中添加数据rowkey
Get get=new Get(Bytes.toBytes("1001"));
//5.获取结果
Result result=student.get(get);
//6.遍历
Cell[] cells=result.rawCells();
for(Cell cell:cells){
//获取具体的值
System.out.println("列"+Bytes.toString(CellUtil.cloneRow(cell)));
System.out.println("族"+Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println(""+Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("value"+Bytes.toInt(CellUtil.cloneValue(cell)));
}
//7.关闭连接
conn.close();
)
(4)删除数据
//添加数据DML
@Test
public void putData2Table()()
//1.获取HBase连接配置
HBaseConfiguration conf=HBaseConfiguration.create();
conf.set("hbase.zookeeper","nodefour");
conf.set("hbase.zookeeper.property.clientPort","2181");
//2.创建连接
Connection conn=ConnectionFactory.createConnection(conf);
//3.获取table
Admin admin=conn.getAdmin();
//4.禁用表
admin.disableTable(TableName.valueOf("student"));
//5.删除表
admin.deleteTable(TableName.valueOf("student"));
//6.关闭连接
conn.close();
)