前面介绍了HBase的shell命令操作,现在介绍Hbase java API操作。
开发环境:
IDE:Eclipse
hadoop:hadoop-1.1.2
hbase: hbase-0.94.7-security
1、获取Configuration
private static Configuration getConfiguration() {
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.rootdir", "hdfs://hadoop0:9000/hbase");
//在eclipse中必须添加这个属性值
conf.set("hbase.zookeeper.quorum", "hadoop0");
return conf;
}
2、创建表
private static void createTable(String tableName, String columnFamily) throws Exception{
HBaseAdmin admin = new HBaseAdmin(getConfiguration());
if (admin.tableExists(tableName)) {
System.out.println("table exists.");
} else {
HTableDescriptor descriptor = new HTableDescriptor(tableName);
descriptor.addFamily(new HColumnDescriptor(columnFamily));
admin.createTable(descriptor);
System.out.println("create table success!");
}
}
3、添加一条记录
public static void putRec(String tableName, String row, String columnFamily,
String column,String data) throws Exception {
HTable hTable = new HTable(getConfiguration(), tableName);
Put put = new Put(Bytes.toBytes(row));
put.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(data));
hTable.put(put);
System.out.println("rowkey =" + row + ",columnFamily = "
+ columnFamily + ", column = " + column
+ ", data = " + data);
}
public static void getRec(String tableName, String rowKey) throws IOException {
HTable hTable = new HTable(getConfiguration(), tableName);
Get get = new Get(Bytes.toBytes(rowKey));
Result result = hTable.get(get);
System.out.println("Get = " + result);
}
public static void scanTable (String tableName) throws Exception {
HTable hTable = new HTable(getConfiguration(), tableName);
Scan scan = new Scan();
ResultScanner scanner =hTable.getScanner(scan);
for (Result result : scanner) {
System.out.println("scan--->" + result);
}
}
6、删除表
public static void dropTable(String tableName) throws Exception {
HBaseAdmin admin = new HBaseAdmin (getConfiguration());
if (admin.tableExists(tableName)) {
try {
admin.disableTable(tableName);
admin.deleteTable(tableName);
} catch (Exception e) {
e.printStackTrace();
System.out.println("drop table " + tableName + "failed!!");
}
}
System.out.println("drop table" + tableName + "success !!");
}
7、驱动代码
public static void main(String[] args) throws Exception {
String tableName = "person";
String columnFamily = "info";
String rowKey = "robin";
createTable(tableName, columnFamily);
putRec(tableName, rowKey, columnFamily, "birthday", "1988-11-29");
putRec(tableName, rowKey, columnFamily, "age", "12");
getRec(tableName, rowKey);
scanTable(tableName);
dropTable(tableName);
}