首先第一步是连接hbase

    // 与HBase数据库的连接对象
    Connection connection;

    // 数据库元数据操作对象
    Admin admin;
    {
	    Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","tdh-manager01,tdh-manager02,tdh-data01");
        conf.set("zookeeper.znode.parent", "/hyperbase1");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        // 取得一个数据库连接对象
        try {
			connection = ConnectionFactory.createConnection(conf);
			admin = connection.getAdmin();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
       
    }

连接如果需要kerberos认证,需要给定core-site.xml、hdfs-site.xml、hbase-site.xml和keytab、config文件

代码:

/*开启连接*/
    {
        Configuration config = HBaseConfiguration.create();
        //String path="C:\\Users\\chen\\Desktop\\新建文件夹\\hbase";
        String path="/data/jar/bxm-label-center/config/hbase"; //后续需要修改文件路径
        //System.setProperty("hadoop.home.dir", "D:\\dfgx\\hadoop-2.7.7");
        config.addResource(new Path(path + File.separator + "core-site.xml"));
        config.addResource(new Path(path + File.separator + "hdfs-site.xml"));
        config.addResource(new Path(path + File.separator + "hbase-site.xml"));
        try {
            //需要修改文件名字和文件的路径
            LoginUtil.setJaasConf(ZOOKEEPER_DEFAULT_LOGIN_CONTEXT_NAME, USERNAME, path + File.separator + "guangda.keytab");
            LoginUtil.setZookeeperServerPrincipal(ZOOKEEPER_SERVER_PRINCIPAL_KEY,
                    ZOOKEEPER_DEFAULT_SERVER_PRINCIPAL);
            LoginUtil.login(USERNAME, path + File.separator + "guangda.keytab",
                    path + File.separator + "krb5.conf", config);
            connection = ConnectionFactory.createConnection(config);
            admin = connection.getAdmin();
            //selectTables();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

第二就可以根据实现增删改查

2.1在hbase里面创建一张表

/**
     * 创建表
     */

    public void createTable() throws IOException{

        System.out.println("---------------创建表 START-----------------");

        // 数据表表名
        String tableNameString = "t_book";

        // 新建一个数据表表名对象
        TableName tableName = TableName.valueOf(tableNameString);

        // 如果需要新建的表已经存在
        if(admin.tableExists(tableName)){

            System.out.println("表已经存在!");
        }
        // 如果需要新建的表不存在
        else{

            // 数据表描述对象
            HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);

            // 列族描述对象
            HColumnDescriptor family= new HColumnDescriptor("base");;

            // 在数据表中新建一个列族
            hTableDescriptor.addFamily(family);

            // 新建数据表
            admin.createTable(hTableDescriptor);
        }

        System.out.println("---------------创建表 END-----------------");
    }

2.2  查询一行数据

 /**
     * 按行键查询表数据
     */

    public void queryTableByRowKey(String name) throws IOException{

        System.out.println("---------------按行键查询表数据 START-----------------");
        int code=name.hashCode();
        // 取得数据表对象
        Table table = connection.getTable(TableName.valueOf("dfgx:dianxin_video"));
      //  put = new Put();
        // 新建一个查询对象作为查询条件
        Get get = new Get(Bytes.toBytes(String.valueOf( name.hashCode())));

        // 按行键查询数据
        Result result = table.get(get);

        byte[] row = result.getRow();

        List<Cell> listCells = result.listCells(); 
        byte[] familyArray =null;
        byte[] qualifierArray=null ;
        byte[] valueArray = null;
        
        for (Cell cell : listCells) {

             familyArray = cell.getFamilyArray();
             qualifierArray = cell.getQualifierArray();
             valueArray = cell.getValueArray();
        }

        System.out.println("---------------按行键查询表数据 END-----------------");

    }

2.3查询整表数据

/**
     * 查询整表数据
     */
     
     public void queryTable() throws IOException{

        System.out.println("---------------查询整表数据 START-----------------");

        // 取得数据表对象
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 取得表中所有数据
        ResultScanner scanner = table.getScanner(new Scan());

        // 循环输出表中的数据
        for (Result result : scanner) {

            byte[] row = result.getRow();
            System.out.println("row key is:" + new String(row));

            List<Cell> listCells = result.listCells();
            for (Cell cell : listCells) {

                byte[] familyArray = cell.getFamilyArray();
                byte[] qualifierArray = cell.getQualifierArray();
                byte[] valueArray = cell.getValueArray();

                System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                             + new String(valueArray));
            }
        }

        System.out.println("---------------查询整表数据 END-----------------");

    }

2.4 按照条件查询数据

/**
     * 按条件查询表数据
     */

    public void queryTableByCondition() throws IOException{

        System.out.println("---------------按条件查询表数据 START-----------------");

        // 取得数据表对象
        Table table = connection.getTable(TableName.valueOf("testdfgx:dianxin_call_info"));

        // 创建一个查询过滤器
        Filter filter = new SingleColumnValueFilter(Bytes.toBytes("base"), Bytes.toBytes("name"), 
                                                    CompareOp.EQUAL, Bytes.toBytes("bookName6"));

        // 创建一个数据表扫描器
        Scan scan = new Scan();

        // 将查询过滤器加入到数据表扫描器对象
        scan.setFilter(filter);

        // 执行查询操作,并取得查询结果
        ResultScanner scanner = table.getScanner(scan);
       
        // 循环输出查询结果
        for (Result result : scanner) {
            byte[] row = result.getRow();
            System.out.println("row key is:" + new String(row));

            List<Cell> listCells = result.listCells();
            for (Cell cell : listCells) {

                byte[] familyArray = cell.getFamilyArray();
                byte[] qualifierArray = cell.getQualifierArray();
                byte[] valueArray = cell.getValueArray();

                System.out.println("row value is:" + new String(familyArray) + new String(qualifierArray) 
                                                                             + new String(valueArray));
            }
        }
        
        System.out.println("---------------按条件查询表数据 END-----------------");

    }

2.5 清空表数据

/**
     * 清空表
     */

    public void truncateTable() throws IOException{

        System.out.println("---------------清空表 START-----------------");

        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("dfgx:dianxin_video");

        // 设置表状态为无效
        admin.disableTable(tableName);
        // 清空指定表的数据
        admin.truncateTable(tableName, true);

        System.out.println("---------------清空表 End-----------------");
    }

2.6删除表

/**
     * 删除表
     */

    public void deleteTable() throws IOException{

        System.out.println("---------------删除表 START-----------------");

        // 设置表状态为无效
        admin.disableTable(TableName.valueOf("t_book"));
        // 删除指定的数据表
        admin.deleteTable(TableName.valueOf("t_book"));

        System.out.println("---------------删除表 End-----------------");
    }

2.7删除某行数据

/**
     * 删除行
     */

    public void deleteByRowKey() throws IOException{

        System.out.println("---------------删除行 START-----------------");

        // 取得待操作的数据表对象
        Table table = connection.getTable(TableName.valueOf("t_book"));

        // 创建删除条件对象
        Delete delete = new Delete(Bytes.toBytes("row2"));

        // 执行删除操作
        table.delete(delete);

        System.out.println("---------------删除行 End-----------------");

    }

2.8 新建和删除列族

 /**
     * 新建列族
     */
    
    public void addColumnFamily() throws IOException{

        System.out.println("---------------新建列族 START-----------------");

        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("t_book");

        // 创建列族对象
        HColumnDescriptor columnDescriptor = new HColumnDescriptor("more");

        // 将新创建的列族添加到指定的数据表
        admin.addColumn(tableName, columnDescriptor);

        System.out.println("---------------新建列族 END-----------------");
    }

    /**
     * 删除列族
     */
    
    public void deleteColumnFamily() throws IOException{

        System.out.println("---------------删除列族 START-----------------");

        // 取得目标数据表的表名对象
        TableName tableName = TableName.valueOf("t_book");

        // 删除指定数据表中的指定列族
        admin.deleteColumn(tableName, "more".getBytes());

        System.out.println("---------------删除列族 END-----------------");
    }

2.9 插入一行数据

/**
     * 插入数据
     * @throws Exception 
     */
 
    public void insert(String filename,String savename,byte[] address) throws Exception{
    	 System.out.println("---------------插入数据 START-----------------");
    	 	System.out.println("filename="+filename);
	        // 取得一个数据表对象
	        Table table = connection.getTable
	        		(TableName.valueOf("dfgx:dianxin_video"));
	        //int code=filename.hashCode();
	        // 需要插入数据库的数据集合
	      //  List<Put> putList = new ArrayList<Put>();
	        byte[] family1 = Bytes.toBytes("f");
	        Put put;
	        put = new Put(Bytes.toBytes(filename));
	        put.addColumn(family1,Bytes.toBytes("file_content"), address);//存储语音文件
	        table.put(put);

	        System.out.println("---------------插入数据 END-----------------");

    }

//项目中实践代码区域---rowkeyRange是{cusyid,custid+"}"}

 public List<Map<String,String>> selectList(String tableName, Filter filter,String[] rowKeyRange){

        try{
            Table table = connection.getTable(TableName.valueOf(tableName));
            Scan s = new Scan();
            if(rowKeyRange != null){
                if(rowKeyRange.length>0){
                    s.setStartRow(rowKeyRange[0].getBytes());
                }
                if(rowKeyRange.length>1){
                    s.setStopRow(rowKeyRange[1].getBytes());
                }
            }
            s.setFilter(filter);
            s.addFamily("cf1".getBytes()); //只在这个列族下操作
            ResultScanner results = table.getScanner(s);
            List<Map<String,String>> list = new ArrayList<>();
            //获取多行内容
            System.out.println(results);
            for(Result r:results){
                byte[] row = r.getRow();
                System.out.println("本次 row key is " + new String(row));
                //把每一行内容存在map
                Map<String,String>  map = new HashMap<>();
                for (Cell c : r.listCells()){
                    String key = Bytes.toString(CellUtil.cloneQualifier(c));
                    String value = Bytes.toString(CellUtil.cloneValue(c));
                    System.out.println(key+":"+value);
                    map.put(key,value);
                }
                list.add(map);
            }
            table.close();
            connection.close();
            return list;
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
        //关闭连接
        try {
            connection.close();
        } catch (IOException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐