DML主要包括INSERT、UPDATE、DELETE三种指令,一般情况下,数据库的初始基本操作通常称为 CRUD (create, read, update, and delete), 指的是 增、查、改、删四种操作。HBase 中有与之对应的的一组操作,由Table interface 接口提供。
TestHTable.java 测试类
public class TestHTable {
private static final String TABLE_NAME = "MY_HBASE_TABLE_TADMIN";
private static final String CF_DEFAULT = "DEFAULT_COLUMN_FAMILY";
/**
* 插入记录
*/
public static void putRecord() throws IOException {
//Create the required configuration
Configuration conf = HBaseConfiguration.create();
//Instantiate a new client.
Connection conn = ConnectionFactory.createConnection(conf);
Table table = conn.getTable(TableName.valueOf(TABLE_NAME));
//Create put with specific row.
Put put = new Put(Bytes.toBytes("rowkey1"));
//Add column, put <table>,<rowkey>,<family:column>,<value>
put.addColumn(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes("name"), Bytes.toBytes("hbase1"));
put.addColumn(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes("version"), Bytes.toBytes("2.0.3"));
//Store row with column into the HBase table.
table.put(put);
//Close table and connection instances to free resources.
table.close();
conn.close();
}
/**
* 获取记录,语法:get <table>,<rowkey>,[<family:column>,....]
*/
public static void getRecord() throws IOException {
//Create the required configuration
Configuration conf = HBaseConfiguration.create();
//Instantiate a new client.
Connection conn = ConnectionFactory.createConnection(conf);
Table table = conn.getTable(TableName.valueOf(TABLE_NAME));
// Create get with specific row.
Get get = new Get(Bytes.toBytes("rowkey1"));
// Add a column to the get.
//get.addColumn(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes("name"));
// Retrieve row with selected columns from HBase.
Result result = table.get(get);
System.out.println("Result: " + result);
CellScanner scanner = result.cellScanner();
while (scanner.advance()) {
System.out.println("Get Cell: " + scanner.current());
}
// Get a specific value for the given column.
byte[] val1 = result.getValue(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes("name"));
byte[] val2 = result.getValue(Bytes.toBytes(CF_DEFAULT), Bytes.toBytes("version"));
System.out.println("name: " + Bytes.toString(val1));
System.out.println("version: " + Bytes.toString(val2));
//Close table and connection instances to free resources.
table.close();
conn.close();
}
public static void main(String[] args) throws IOException {
//putRecord();
getRecord();
}
}
运行结果:插入数据
运行结果:查询数据