技术开发 频道

基于Java的HBase客户端编程

  3. HBase基本操作代码示例

  (1)初始化配置

1 private static Configuration conf = null;
2 /**
3  * 初始化配置
4  
*/
5 static {
6     conf = HBaseConfiguration.create();
7 }

  (2)创建表

1 /**
2  * 创建表操作
3  *
@throws IOException
4  
*/
5 public void createTable(String tablename, String[] cfs) throws IOException {
6     HBaseAdmin admin = new HBaseAdmin(conf);
7     if (admin.tableExists(tablename)) {
8         System.out.println("表已经存在!");
9     }
10     else {
11         HTableDescriptor tableDesc = new HTableDescriptor(tablename);
12         for (int i = 0; i < cfs.length; i++) {
13             tableDesc.addFamily(new HColumnDescriptor(cfs[i]));
14         }
15         admin.createTable(tableDesc);
16         System.out.println("表创建成功!");
17     }
18 }

  (3)删除表

1 /**
2  * 删除表操作
3  *
@param tablename
4  *
@throws IOException
5  
*/
6 public void deleteTable(String tablename) throws IOException {
7     try {
8         HBaseAdmin admin = new HBaseAdmin(conf);
9         admin.disableTable(tablename);
10         admin.deleteTable(tablename);
11         System.out.println("表删除成功!");
12     } catch (MasterNotRunningException e) {
13         e.printStackTrace();
14     } catch (ZooKeeperConnectionException e) {
15         e.printStackTrace();
16     }
17 }

  (4)插入一行记录

1 /**
2  * 插入一行记录
3  *
@param tablename
4  *
@param cfs
5  
*/
6 public void writeRow(String tablename, String[] cfs) {
7     try {
8         HTable table = new HTable(conf, tablename);
9         Put put = new Put(Bytes.toBytes("rows1"));
10         for (int j = 0; j < cfs.length; j++) {
11             put.add(Bytes.toBytes(cfs[j]),
12                     Bytes.toBytes(String.valueOf(1)),
13                     Bytes.toBytes("value_1"));
14             table.put(put);
15         }
16     } catch (IOException e) {
17         e.printStackTrace();
18     }
19 }
0
相关文章