import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
public class Hbase {
public static final String TABLE_NAME = "users";
public static final String FAMILY_NAME1 = "info";
public static final String COLUMN_NAME = "age";
public static void main(String[] args) throws Throwable {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://hadoop0:9000/hbase");
conf.set("hbase.zookeeper.quorum", "hadoop0");
HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);
HTable hTable = new HTable(conf, TABLE_NAME);
createTable(hBaseAdmin);
//putRecord(hTable);
//getRecord(hTable);
scanRecord(hTable);
// dropTable(hBaseAdmin);
}
//遍历整个表
private static void scanRecord(HTable hTable) throws Exception {
Scan scan = new Scan();
ResultScanner resultScanner = hTable.getScanner(scan);
for(Result result : resultScanner) {
byte[] age = result.getValue(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes());
System.out.println(new String(age));
}
}
//得到某一条记录
private static void getRecord(HTable hTable) throws Exception {
Get get = new Get("xiaoming".getBytes());
Result result = hTable.get(get);
byte[] age = result.getValue(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes());
System.out.println(new String(age));
}
//往表中存入数据
private static void putRecord(HTable hTable) throws Exception {
Put put = new Put("xiaoming".getBytes());
put.add(FAMILY_NAME1.getBytes(), COLUMN_NAME.getBytes(), "30".getBytes());
hTable.put(put);
}
//删除表
private static void dropTable(HBaseAdmin hBaseAdmin) throws Exception {
if(hBaseAdmin.tableExists(TABLE_NAME)) {
hBaseAdmin.disableTable(TABLE_NAME);
hBaseAdmin.deleteTable(TABLE_NAME);
}
}
//创建表
private static void createTable(HBaseAdmin hBaseAdmin) throws Throwable {
if(!hBaseAdmin.tableExists(TABLE_NAME)) {
HTableDescriptor hTableDescriptor = new HTableDescriptor(TABLE_NAME);
HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(FAMILY_NAME1);
hTableDescriptor.addFamily(hColumnDescriptor);
hBaseAdmin.createTable(hTableDescriptor);
}
}
}
Hadoop学习笔记(十六)---HBase JAVA API
最新推荐文章于 2024-08-31 10:44:02 发布