熟悉常用的HBASE 操作
阿新 • • 發佈:2018-10-12
wke trac clas config add lose exception class except
1.查看所有表
package cn.edu.zucc.hbase; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.client.Connection;import org.apache.hadoop.hbase.client.ConnectionFactory; public class ListTables { public static Configuration configuration; public static Connection connection; public static Admin admin; public static void listTables() throws IOException { init(); HTableDescriptor[] hTableDescriptors= admin.listTables(); for (HTableDescriptor hTableDescriptor : hTableDescriptors) { System.out.println("表名:" + hTableDescriptor.getNameAsString()); } close(); } public static void init() { configuration = HBaseConfiguration.create(); configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase"); try { connection = ConnectionFactory.createConnection(configuration); admin = connection.getAdmin(); } catch (IOException e) { e.printStackTrace(); } } public static void close() { try { if (admin != null) { admin.close(); } if (connection != null) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { listTables(); } catch (IOException e) { e.printStackTrace(); } } }
2.添加一行數據
package cn.edu.zucc.hbase; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import java.io.IOException; public class InsertRow { public static Configuration configuration; public static Connection connection; public static Admin admin; public static void insertRow(String tableName, String rowKey, String colFamily, String col, String val) throws IOException { init(); Table table = connection.getTable(TableName.valueOf(tableName)); Put put = new Put(rowKey.getBytes()); put.addColumn(colFamily.getBytes(), col.getBytes(), val.getBytes()); table.put(put); table.close(); close(); } public static void init() { configuration = HBaseConfiguration.create(); configuration.set("hbase.rootdir", "hdfs://localhost:9000/hbase"); try { connection = ConnectionFactory.createConnection(configuration); admin = connection.getAdmin(); } catch (IOException e) { e.printStackTrace(); } } public static void close() { try { if (admin != null) { admin.close(); } if (null != connection) { connection.close(); } } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { try { insertRow("student", "20160000", "score", "math", "100"); } catch (IOException e) { e.printStackTrace(); } } }
熟悉常用的HBASE 操作