吴超老师课程--HBASE的Java_API
public static void main(String[] args) throws IOException {String tableName="hbase_tb";
String columnFamily="cf";
HBaseTestCase.create(tableName, columnFamily);
HBaseTestCase.put(tableName, "row1", columnFamily, "cl1", "data");
HBaseTestCase.get(tableName, "row1");
HBaseTestCase.scan(tableName);
HBaseTestCase.delete(tableName);
}
1 //hbase操作必备2 private static Configuration getConfiguration() {
3 Configuration conf = HBaseConfiguration.create();
4 conf.set("hbase.rootdir", "hdfs://hadoop:9000/hbase");
5 //使用eclipse时必须添加这个,否则无法定位
6 conf.set("hbase.zookeeper.quorum", "hadoop");
7 return conf;
8 }
1 //创建一张表2 public static void create(String tableName, String columnFamily) throws IOException{
3 HBaseAdmin admin = new HBaseAdmin(getConfiguration());
4 if (admin.tableExists(tableName)) {
5 System.out.println("table exists!");
6 }else{
7 HTableDescriptor tableDesc = new HTableDescriptor(tableName);
8 tableDesc.addFamily(new HColumnDescriptor(columnFamily));
9 admin.createTable(tableDesc);
10 System.out.println("create table success!");
11 }
12 }
1 //添加一条记录2 public static void put(String tableName, String row, String columnFamily, String column, String data) throws IOException{
3 HTable table = new HTable(getConfiguration(), tableName);
4 Put p1 = new Put(Bytes.toBytes(row));
5 p1.add(Bytes.toBytes(columnFamily), Bytes.toBytes(column), Bytes.toBytes(data));
6 table.put(p1);
7 System.out.println("put'"+row+"',"+columnFamily+":"+column+"','"+data+"'");
8 }
1 //读取一条记录2 public static void get(String tableName, String row) throws IOException{
3 HTable table = new HTable(getConfiguration(), tableName);
4 Get get = new Get(Bytes.toBytes(row));
5 Result result = table.get(get);
6 System.out.println("Get: "+result);
7 }
1 //显示所有数据2 public static void scan(String tableName) throws IOException{
3 HTable table = new HTable(getConfiguration(), tableName);
4 Scan scan = new Scan();
5 ResultScanner scanner = table.getScanner(scan);
6 for (Result result : scanner) {
7 System.out.println("Scan: "+result);
8 }
9 }
1 //删除表2 public static void delete(String tableName) throws IOException{
3 HBaseAdmin admin = new HBaseAdmin(getConfiguration());
4 if(admin.tableExists(tableName)){
5 try {
6 admin.disableTable(tableName);
7 admin.deleteTable(tableName);
8 } catch (IOException e) {
9 e.printStackTrace();
10 System.out.println("Delete "+tableName+" 失败");
11 }
12 }
13 System.out.println("Delete "+tableName+" 成功");
14 }
以上是 吴超老师课程--HBASE的Java_API 的全部内容, 来源链接: utcz.com/z/391806.html