【方法】给表中添加数据:
private static void putData(String tableName,String rowKey,String cf,String cn,String value) throws IOException {
//获取Table对象
Table table = connection.getTable(TableName.valueOf(tableName));
//创建put对象
Put put = new Put(Bytes.toBytes(rowKey));
//添加数据
put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), Bytes.toBytes(value));
//插入数据
table.put(put);
//关闭表连接
table.close();
}
注: 一个rowkey对应一个put对象,若要为N个rowkey批量添加数据,则需要创建 N个 put 对象
指定rowKey查询(打印出该行的列族名、列名、值):
private static void getData(String tableName,String rowKey,String cf,String cn) throws IOException {
//获取表对象
Table table = connection.getTable(TableName.valueOf(tableName));
//创建get对象
Get get = new Get(Bytes.toBytes(rowKey));
//为get对象设置列限制
get.addClomn(Bytes.toBytes(cf),Bytes.toBytes(cn));
//为get对象设置获取的版本数(设系统设置的版本数为3,则无参表示获取3个版本,传参则表示该数量[3以内]的版本)
get.setMaxVersions();
//获取数据
Result result = table.get(get);
//解析result
for(Cell cell:result.rowCells()){
System.out.println("CF:" + Bytes.toString(CellUtil.cloneFamily(cell))
+ ",CN:" + Bytes.toString(CellUtil.cloneQualifier(cell))
+ ",Value:" + Bytes.toString(CellUtil.cloneValue(cell)));
}
//关闭表连接
table.close();
}
【方法】扫描表中数据(开始行--->结束行):
private static void scanTable(String tableName, String startRow, String stopRow) throws IOException{
//获取表对象
Table table = connection.getTable(TableName.valueOf(tableName));
//创建Scan对象,添加构造参数:开始行(包含),结束行(不包含)
Scan scan = new Scan(Bytes.toBytes(startRow),Bytes.toBytes(stopRow));
//扫描表
ResultScanner results = table.getScanner(scan);
//解析results
for(Result result : results){
//解析result
for(Cell cell : result.rawCells()){
System.out.println("CF:" + Bytes.toString(CellUtil.cloneFamily(cell))
+ ",CN" + Bytes.toString(CellUtil.cloneQualifier(cell))
+ ",value" + Bytes.toString(CellUtil.cloneValue(cell))
);
}
}
//关闭表连接
table.close();
}
【方法】删除数据
private static void deleteTable(String tableName, String rowKey, String cf, String cn) throws IOException{
//获取表对象
Table table = connection.getTable(TableName.valueOf(tableName));
//创建Delete对象
Delete delete = new Delete(Bytes.toBytes(rowKey));
//指定删除该列族的数据,删除所有版本,若加了时间戳参数,则删除该时间戳之前的所有版本
delete.addFamily(Bytes.toBytes(cf));
//指定删除该列族的数据,删除一个版本,有个时间戳参数,指删除该时间戳所对应的版本
delete.addFamilyVersion(Bytes.toBytes(cf),1000000000000);
//指定删除该列的数据,删除所有版本[推荐使用],若加了时间戳参数,则删除该时间戳之前的所有版本
delete.addColumns(Bytes.toBytes(cf),Bytes.toBytes(cn));
//指定删除该列的数据,删除最新一个版本[不推荐使用],若加了时间戳参数,则删除该时间戳所对应的版本
delete.addColumn(Bytes.toBytes(cf),Bytes.toBytes(cn));
//删除数据
table.delete(delete);
//关闭表连接
table.close();
}