1. 程式人生 > 其它 >HBase資料庫基礎操作

HBase資料庫基礎操作

實驗要求:

根據上面給出的學生表Student的資訊,執行如下操作:

  • 用Hbase Shell命令建立學生表Student;
  create 'student','name', 'score'
  put 'student','01','name:name','zhangsan'
  put 'student','01','score:English','69'
  put 'student','01','score:Math','86'
  put 'student','01','score:Computer,'77'
  put 'student','02','name:name','
lisi' put 'student','02','score:English','55' put 'student','02','score:Math','100' put 'student','02','score:Computer','88'
  • 用scan命令瀏覽Student表的相關資訊;
scan 'student'
  • 查詢zhangsan的Computer成績;\
get 'student','01','score:Computer'
  • 修改lisi的Math成績,改為95;
put 'student' ,'02','score:Math','95'

核心程式碼:

//5.插入資料
public static void putData(String tableName, String rowKey,
                              String columnFamily, String
                                      column, String value) throws IOException{
    //獲取表物件
    Table table=connection.getTable(TableName.valueOf(tableName));
    
//建立put物件 Put put=new Put(Bytes.toBytes(rowKey)); //給put物件賦值 put.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(column),Bytes.toBytes(value)); put.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(column),Bytes.toBytes(value)); put.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(column),Bytes.toBytes(value)); put.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(column),Bytes.toBytes(value)); //新增資料 table.put(put); //關閉連線 table.close(); } public static void main(String[] args) throws IOException { //5.插入資料 putData("student","03","name","name","scofield"); putData("student","03","score","English","45"); putData("student","03","score","Math","89"); putData("student","03","score","Computer","100"); //關閉資源 close(); } }
  • 獲取scofield的English成績資訊。
public static void getData(String tableName,String rowKey,String columnFamily,String column) throws IOException{
    //獲取物件
    Table table=connection.getTable(TableName.valueOf(tableName));
    //建立GET物件
    Get get=new Get(Bytes.toBytes(rowKey));
        //指定獲取的列族
        get.addFamily(Bytes.toBytes(columnFamily));
        //指定列族和列
        get.addColumn(Bytes.toBytes(columnFamily),Bytes.toBytes(column));
    //獲取資料
    Result result=table.get(get);
    //解析result
    for (Cell cell : result.rawCells()) {
        //列印資料
        System.out.println("columnFamily:"+Bytes.toString(CellUtil.cloneFamily(cell))+
                ",column:"+Bytes.toString(CellUtil.cloneQualifier(cell))+
                ",value:"+Bytes.toString(CellUtil.cloneValue(cell)));
    }
    //關閉表連線
    table.close();
}
public static void main(String[] args) throws IOException {
        //獲取資料
            //獲取單行資料
            getData("student","03","score","English");
        //關閉資源
          close();
    }
}