1、插入数据
public static void putData(String tableName, String rk, String cf, String cn, String value) throws IOException {
//1、获取表对象
Table table = connection.getTable(TableName.valueOf(tableName));
//2、创建put对象
Put put = new Put(Bytes.toBytes(rk));
//3、给put对象赋值:byte [] family, byte [] qualifier, byte [] value
put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), Bytes.toBytes(value));
//4、插入数据
table.put(put);
//5、关闭表连接
table.close();
/*
* 若要put多个对象有两种方法
* 1、put.addColumn时多put是可以创建多个对象的
* 2、设置多个put,插入是插入put的列表
* */
}
需要注意的地方有3个:
①:要创建对象需要对表进行修改,就不能用admin了,需要用connection得到table对象对表进行操作
②:要插入数据需要put对象,而put对象需要的值都要是byte[]类型的,所以需要使用HBase提供的工具类Bytes进行类型转换
③:这里不统一关闭资源的原因是,每次操作的表对象可能不同,所以每次使用完都需要关闭资源
测试:
public static void main(String[] args) throws IOException {
putData("stu2", "1001", "info1", "age", "19");
}
结果:
插入成功
2、get表中的数据
public static void getData(String tableName, String rk, String cf, String cn) throws IOException {
//创建表最少要有一个rowkey
//1、创建表对象
Table table = connection.getTable(TableName.valueOf(tableName));
//2、创建get对象
Get get = new Get(Bytes.toBytes(rk));
//3.1、给get设置指定列族和列
get.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn));
//3.2、给get设置指定列族
// get.addFamily(Bytes.toBytes(cf));
//4、将get对象传给table,获取result对象
Result results = table.get(get);
//5、打印所需要的值
for(Cell cell : results.rawCells()){
System.out.println("CF:" + Bytes.toString(CellUtil.cloneFamily(cell)) +
",CN:" + Bytes.toString(CellUtil.cloneQualifier(cell)) +