publicvoidtestCreate()throws Exception Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum","hadoop01,hadoop02,hadoop03");//制定zookeeper的地址 HBaseAdmin admin = new HBaseAdmin(conf);//指定要操作的HBase集群 HTableDescriptor td = new HTableDescriptor("user");//设定表名字 HColumnDescriptor cd = new HColumnDescriptor("info");//设定列族,可以指定多个列族 cd.setMaxVersions(10); td.addFamily(cd); admin.createTable(td); admin.close(); }
查询数据
查询一个值
1 2 3 4 5 6 7 8 9
publicvoidtestGet()throws Exception{ HTable table = new HTable(conf, "user"); Get get = new Get(Bytes.toBytes("rk0001"));//取表中行键为rk0001的行 get.setMaxVersions(5); Result result = table.get(get); String r = Bytes.toString(result.getValue(Bytes.toBytes("info"),Bytes.toBytes("money")));//指定列族和列的详细标识 System.out.println(r); table.close(); }
查询多个值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicvoidtestScan()throws Exception{ HTable table = new HTable(conf, "user"); Scan scan = new Scan(Bytes.toBytes("rk0001"), Bytes.toBytes("rk0002"));//指定行键的一个范围 scan.addFamily(Bytes.toBytes("info")); ResultScanner scanner = table.getScanner(scan); for(Result r : scanner){ for(KeyValue kv : r.list()){//同时输出列族和列的详细标识 String family = new String(kv.getFamily()); System.out.println(family); String qualifier = new String(kv.getQualifier()); System.out.println(qualifier); System.out.println(new String(kv.getValue())); } } table.close(); }
插入数据
1 2 3 4 5 6 7 8
publicvoidtestPut()throws Exception{ HTable table = new HTable(conf, "user"); Put put = new Put(Bytes.toBytes("rk0003"));//指定行键 //三个参数的分别代表:列族,列的详细标识,value,也有四个参数的方法,第四个参数指的是时间戳 put.add(Bytes.toBytes("info"), Bytes.toBytes("name"), Bytes.toBytes("liuyan")); table.put(put); table.close(); }
删除数据
1 2 3 4 5 6 7
publicvoidtestDel()throws Exception{ HTable table = new HTable(conf, "user"); Delete del = new Delete(Bytes.toBytes("rk0001"));//指定行键 del.deleteColumn(Bytes.toBytes("data"), Bytes.toBytes("pic"));//如果不执行改方法,会将这整行全部删除 table.delete(del); table.close(); }