hbaseAPI測試
pom.xml
<dependencies> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-server</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.apache.hbase</groupId> <artifactId>hbase-client</artifactId> <version>1.3.1</version> </dependency> </dependencies>
public class TestHbaseAPI_01 {
public static void main(String[] args) {
//構建config配置對象
Configuration conf = HBaseConfiguration.create();
try {
//獲取hbase連接對象
Connection conn = ConnectionFactory.createConnection(conf);
//System.out.println(conn);
//獲取操作對象:Admin
// HBaseAdmin admin = new HBaseAdmin(conn);
Admin admin = conn.getAdmin();
//操作數據庫
//判斷命名空間是否存在
try {
NamespaceDescriptor nameSpace = admin.getNamespaceDescriptor("wjy");
} catch (NamespaceNotFoundException e) {
//創建表空間
NamespaceDescriptor nd = NamespaceDescriptor.create("wjy").build();
admin.createNamespace(nd);
}
//判斷表是否存在
TableName tableName = TableName.valueOf("wjy:student");
boolean flag = admin.tableExists(tableName);
if (flag) {
//存在表,操作表
//指定表對對象
Table table = conn.getTable(tableName);
//查詢數據
Get get = new Get(Bytes.toBytes("1001"));
Result result = table.get(get);
if (!result.isEmpty()) {
System.out.println(Bytes.toString(result.getRow()));
System.out.println(Bytes.toString(result.getValue(Bytes.toBytes("cf"),Bytes.toBytes("name"))));
}
} else {
//不存在,創建表
//創建表描述
HTableDescriptor tb = new HTableDescriptor(tableName);
//增加列族信息
HColumnDescriptor cf = new HColumnDescriptor("cf");
tb.addFamily(cf);
//創建
admin.createTable(tb);
}
//獲取操作的結果
//關閉數據庫連接
} catch (IOException e) {
e.printStackTrace();
}
}
}
命令行查詢數據:
hbase(main):006:0> scan 'wjy:student'
ROW COLUMN+CELL
1001 column=cf:name, timestamp=1584708637639, value=wjy
1 row(s) in 0.0250 seconds
IDEA結果輸出
log4j:WARN No appenders could be found for logger (org.apache.hadoop.security.Groups).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
1001
wjy
Process finished with exit code 0