天天看點

HBase資料庫基礎操作

實驗要求:

HBase資料庫基礎操作

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

  • 用Hbase Shell指令建立學生表Student;
'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'      
HBase資料庫基礎操作
  • 用scan指令浏覽Student表的相關資訊;
scan 'student'      
HBase資料庫基礎操作
  • 查詢zhangsan的Computer成績;\
get 'student','01','score:Computer'      
HBase資料庫基礎操作
  • 修改lisi的Math成績,改為95;
put 'student' ,'02','score:Math','95'      
HBase資料庫基礎操作
HBase資料庫基礎操作

核心代碼:

//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();
    }
}      
HBase資料庫基礎操作
  • 擷取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();
    }
}      
HBase資料庫基礎操作

繼續閱讀