直接上代码:
package an.hbase.operation;
import java.io.IOException;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
public class HbasicOperation {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
/**init the configuration of Hbase*/
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorun", "192.168.12.54");
HBaseAdmin admin = new HBaseAdmin(conf);
/**HBaseAdmin.create() 可以用来创建一张新表,该方法的参数为HTableDescription
* 用来描述表名和相关的列簇。该方法的返回值为HTable类,用于对表进行相关的操作
* */
HTableDescriptor tableDescripter = new HTableDescriptor("tab1".getBytes());
tableDescripter.addFamily(new HColumnDescriptor("fam1"));
admin.createTable(tableDescripter);
HTable table = new HTable(conf,"tab1");
/**HTable.put()可以向表中插入数据,该方法的参数为Put类*
*/
Put putRow1 = new Put("row1".getBytes());
putRow1 .add("fam1".getBytes(),"col1".getBytes(),"val1".getBytes());
table.put(putRow1 );
System.out.println("add row2");
Put putRow2 = new Put("row2".getBytes());
putRow2.add("fam1".getBytes(), "col2".getBytes(), "val2".getBytes());
putRow2.add("fam1".getBytes(), "col3".getBytes(), "val3".getBytes());
table.put( putRow2);
/**HTable.getScanner()可以获得某一个列族的所有数据,
* 该方法返回Result类,Result.getFamiliyAmp()可以获得
* 以列名为key,值为value的映射表,然后就可以以此读取相关的内容了
* */
for(Result row:table.getScanner("fam1".getBytes())){
System.out.format("ROW\t%s\n" , new String(row.getRow()));
for(Map.Entry<byte[], byte[]> entry : row.getFamilyMap("fam1".getBytes()).entrySet()){
String column = new String(entry.getKey());
String value = new String(entry.getValue());
System.out.format("COLUMN\tfam1:%s\t%s\n", column,value);
}//for Map
}//for R
// admin.disableTable("tab1"); //disable the table
//admin.deleteTable("tab1");//delete the table
}
}
java -jar ...jar