Java操作HBase
导入配置文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/20191215163204627.png#pic_left)
代码
public class Demo
{
Admin admin = null;
Connection conn = null;
{
try
{
Configuration conf = HBaseConfiguration.create();
conf.set("hbase.zookeeper.quorum", "hadoop");
conf.set("hbase.zookeeper.property.clientPort", "2181");
conn = ConnectionFactory.createConnection(conf);
admin = conn.getAdmin();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Test
public void isTableExists() throws IOException
{
boolean exists = admin.tableExists(TableName.valueOf("tmpTable"));
System.out.println(exists);
}
@Test
public void createTable() throws IOException
{
HTableDescriptor hTableDescriptor = new HTableDescriptor(TableName.valueOf("tmpTable"));
hTableDescriptor.addFamily(new HColumnDescriptor("cf1"));
hTableDescriptor.addFamily(new HColumnDescriptor("cf2"));
admin.createTable(hTableDescriptor);
}
@Test
public void listTable() throws IOException
{
HTableDescriptor[] hTableDescriptors = admin.listTables();
for (HTableDescriptor tableDescriptor : hTableDescriptors)
{
System.out.println(tableDescriptor.getNameAsString());
}
}
@Test
public void putData2Tabel() throws IOException
{
Table table = conn.getTable(TableName.valueOf("tmpTable"));
Put put = new Put(Bytes.toBytes("1001"));
put.addColumn(Bytes.toBytes("cf1"), Bytes.toBytes("name"), Bytes.toBytes("zhangsan"));
table.put(put);
}
@Test
public void getTable() throws IOException
{
Table table = conn.getTable(TableName.valueOf("tmpTable"));
Get get = new Get(Bytes.toBytes("1001"));
Result result = table.get(get);
Cell[] cells = result.rawCells();
for (Cell cell : cells)
{
System.out.println("row_key : " + Bytes.toString(CellUtil.cloneRow(cell)));
System.out.println("列簇 : " + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("列 : " + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("值 : " + Bytes.toString(CellUtil.cloneValue(cell)));
System.out.println("---------------------------------------------");
}
}
@Test
public void scanTable() throws IOException
{
Table table = conn.getTable(TableName.valueOf("tmpTable"));
ResultScanner scanner = table.getScanner(new Scan());
for (Result result : scanner)
{
Cell[] cells = result.rawCells();
for (Cell cell : cells)
{
System.out.println("row_key : " + Bytes.toString(CellUtil.cloneRow(cell)));
System.out.println("列簇 : " + Bytes.toString(CellUtil.cloneFamily(cell)));
System.out.println("列 : " + Bytes.toString(CellUtil.cloneQualifier(cell)));
System.out.println("值 : " + Bytes.toString(CellUtil.cloneValue(cell)));
System.out.println("---------------------------------------------");
}
}
}
@Test
public void dropTable() throws IOException
{
admin.disableTable(TableName.valueOf("tmpTable"));
admin.deleteTable(TableName.valueOf("tmpTable"));
}
}