近日查看了相关资料后,梳理了一下用java实现hbase的表创建、数据插入、删除表,代码如下:
1、需要的jar包:
commons-codec-1.4.jar
commons-logging-1.0.4.jar
hadoop-0.20.2-core.jar
hbase-0.20.6.jar
log4j-1.2.15.jar
zookeeper-3.2.2.jar
2、代码。
1 package org.myhbase; 2 3 import java.io.IOException; 4 5 import org.apache.hadoop.conf.Configuration; 6 import org.apache.hadoop.hbase.HBaseConfiguration; 7 import org.apache.hadoop.hbase.HColumnDescriptor; 8 import org.apache.hadoop.hbase.HTableDescriptor; 9 import org.apache.hadoop.hbase.KeyValue; 10 import org.apache.hadoop.hbase.client.HBaseAdmin; 11 import org.apache.hadoop.hbase.client.HTable; 12 import org.apache.hadoop.hbase.client.Result; 13 import org.apache.hadoop.hbase.client.ResultScanner; 14 import org.apache.hadoop.hbase.client.Scan; 15 import org.apache.hadoop.hbase.io.BatchUpdate; 16 17 public class HBaseBasic02 { 18 static HBaseConfiguration hbaseConfig=null; 19 static{ 20 Configuration config=new Configuration(); 21 config.set("hbase.zookeeper.quorum","192.168.10.149,192.168.10.44,192.168.10.49"); 22 config.set("hbase.zookeeper.property.clientPort", "2181"); 23 hbaseConfig=new HBaseConfiguration(config); 24 } 25 26 /** 27 * 创建一张表 28 * @throws IOException 29 */ 30 public static void createTable(String tablename) throws IOException{ 31 HBaseAdmin admin = new HBaseAdmin(hbaseConfig); 32 if(admin.tableExists(tablename)){ 33 System.out.println("table Exists!!!"); 34 }else{ 35 HTableDescriptor tableDesc = new HTableDescriptor(tablename); 36 tableDesc.addFamily(new HColumnDescriptor("name:")); 37 admin.createTable(tableDesc); 38 System.out.println("create table ok."); 39 } 40 } 41 42 /** 43 * 删除一张表 44 * @throws IOException 45 */ 46 public static void dropTable(String tablename) throws IOException{ 47 HBaseAdmin admin = new HBaseAdmin(hbaseConfig); 48 admin.disableTable(tablename); 49 admin.deleteTable(tablename); 50 System.out.println("drop table ok."); 51 } 52 53 54 /** 55 * 添加一条数据 56 * @throws IOException 57 */ 58 public static void addData(String tablename) throws IOException{ 59 HTable table=new HTable(hbaseConfig,tablename); 60 BatchUpdate update=new BatchUpdate("Huangyi"); 61 update.put("name:java","http://www.sun.com".getBytes()); 62 table.commit(update); 63 System.out.println("add data ok."); 64 } 65 66 67 /** 68 * 显示所有数据 69 * @throws IOException 70 */ 71 public static void getAllData(String tablename) throws IOException{ 72 HTable table=new HTable(hbaseConfig,tablename); 73 Scan s=new Scan(); 74 ResultScanner rs=table.getScanner(s); 75 for(Result r:rs){ 76 for(KeyValue kv:r.raw()){ 77 System.out.println("rowkey : "+new String(kv.getRow())); 78 System.out.println(new String(kv.getColumn())+" = "+new String(kv.getValue())); 79 } 80 } 81 } 82 83 public static void main(String [] args) throws IOException{ 84 String tablename="table_1"; 85 HBaseBasic02.createTable(tablename); 86 HBaseBasic02.addData(tablename); 87 HBaseBasic02.getAllData(tablename); 88 HBaseBasic02.dropTable(tablename); 89 } 90 91 92 }
点击查看
时间: 2024-12-07 19:16:24