用java去连接mysql、hive、hbase

首先先创建一个maven工程,在main里面创建一个resource目录,并将其设置为Resources模式。把下面的log4j.properties文档放入到resource目录下

	log4j.rootLogger=INFO, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/hadoop.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n

一、java连mysql
1、在resource目录下创建 datasource.properties 文件,用来编写
driver、url、username
/

/加载驱动包
driver=com.mysql.jdbc.Driver

//" IP_ADDRESS : PORT " 处,输入对应的虚机的IP地址及端口号
//" DATABASE " 处,输入对应的数据库
url=jdbc:mysql://" IP_ADDRESS : PORT "/" DATABASE "?useUnicode=true&characterEncoding=utf8&useSSL=true

//" USER_NAME " 处,输入对应的虚机的用户名
username=" USER_NAME "

//" USER_PASSWORD " 处,输入对应的虚机的密码
password=" USER_PASSWORD "
```/
2、创建BaseConfig、BaseDao、Result、Test类,代码如下
BaseConfig类

```java
public class BaseConfig{

    private class Config{

         String driver;
        String url;
         String username;
         String password;

        public Config(String driver,String url, String username, String password) {
            this.driver = driver;
            this.url = url;
            this.username = username;
            this.password = password;
        }
    }

    private Config config;

    {
        try {
            init();
            Class.forName(config.driver);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    public void init() throws Exception {
        String path = Thread.currentThread().getContextClassLoader().getResource("datasource.properties").getPath();
        Properties pro = new Properties();
        pro.load(new FileReader(path));
        String url = pro.getProperty("url");
        if (null==url) {
            throw new Exception("缺少url配置项异常");
        }
        String driver = pro.getProperty("driver","com.mysql.jdbc.Driver");
        
        //" USER_NAME " 处,输入对应的虚机的用户名
		//" USER_PASSWORD " 处,输入对应的虚机的密码
        String username = pro.getProperty("username", " USER_NAME ");
        String password = pro.getProperty("password", " USER_PASSWORD ");

        
        this.config = new Config(driver,url,username,password);
    }

    protected Connection getCon() throws SQLException {
        return DriverManager.getConnection(config.url,config.username,config.password);
    }

    protected void close(AutoCloseable...acs){
        for (AutoCloseable ac : acs) {
            if (ac!=null) {
                try {
                    ac.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

BaseDao类

public class BaseDao extends BaseConfig{
    private PreparedStatement getPst(Connection con,String sql,Object...params) throws SQLException {
        PreparedStatement pst = con.prepareStatement(sql);
        if (params.length>0) {
            for (int i = 0; i < params.length; i++) {
               pst.setObject(i+1,params[i]);
            }
        }
        return pst;
    }

    public Result exeNonQuery(String sql,Object...params){
        Connection con = null;
        PreparedStatement pst=null;
        try {
            con=getCon();
            pst=getPst(con,sql,params);
            return Result.succeed(pst.executeUpdate());
        } catch (SQLException e) {
            return Result.fail();
        }finally {
            close(pst,con);
        }
    }

    public Result exeQuery(String sql,Object...params){
        Connection con=null;
        PreparedStatement pst=null;
        ResultSet rst = null;
        try {
            con=getCon();
            pst=getPst(con,sql,params);
            rst=pst.executeQuery();
            List<List<String>> data = new ArrayList<>();
            if (rst!=null&&rst.next()) {
                final int CC = rst.getMetaData().getColumnCount();
                do{
                    List<String> row = new ArrayList<>(CC);
                    for (int i = 1; i <= CC; i++) {
                        row.add(rst.getObject(i).toString());
                    }
                    data.add(row);
                }while(rst.next());
            }
            return Result.succeed(data);
        } catch (SQLException e) {
            return  Result.fail();
        }finally {
            close(rst,pst,con);
        }
    }
}

Result类

public class Result<T>{

    private boolean err;
    private T data;

    public Result(boolean err, T data) {
        this.err = err;
        this.data = data;
    }

    public boolean isErr() {
        return err;
    }

    public T getData() {
        return data;
    }

    public static <T>Result succeed(T data){
        return  new Result(false,data);
    }
    public static Result fail(){
        return new Result(true,null);
    }
}

Test类

public class Test {
    public static void main(String[] args) {
        BaseDao dao = new BaseDao();
        Result<List<List<String>>> result = dao.exeQuery("select * from student");

        if (!result.isErr()) {
            List<List<String>> data = result.getData();
            for (List<String> row : data) {
                for (String col : row) {
                    System.out.print(col+"\t");
                }
                System.out.println();
            }
        }else{
            System.out.println("查询异常");
        }
    }
}

二、java连接hive
1、第一步还是一样,在resource目录下创建 datasource.properties 文件,用来编写driver、url、username

//加载驱动包
driver=org.apache.hive.jdbc.HiveDriver
		
//" IP_ADDRESS : PORT " 处,输入对应的虚机的IP地址及端口号
//" DATABASE " 处,输入对应的数据库
url=jdbc:hive2://" IP_ADDRESS : PORT "/" DATABASE "	

//" USER_NAME " 处,输入对应的虚机的用户名
username= " USER_NAME "	

2、创建BaseConfig、BaseDao、Result、Test

BaseConfig类

public class BaseConfig {
    private class Config{
        private  String driver;
        private String url;
        private String username;
        private String password;
    }

    private Config config;

    private boolean valid(String url) {
        Pattern p = Pattern.compile("jdbc:\\w+://((\\d{1,3}\\.){3}\\d{1,3}|\\w+):\\d{1,5}/\\w+");
        Matcher m =p.matcher(url);
        return m.matches();
    }

    private void init() throws Exception {
        String path = Thread.currentThread().getContextClassLoader().
                getResource("datasource.properties").getPath();
        Properties pro = new Properties();
        pro.load(new FileReader(path));
        String url = pro.getProperty("url");
        if (null==url || !valid(url)) {
            throw new Exception("no or invalid url exception");
        }
        config = new Config();
        config.url=url;
        config.driver = pro.getProperty("driver", "com.mysql.jdbc.Driver");
        config.username = pro.getProperty("username", "root");
        config.password = pro.getProperty("password", "");
    }

    {
        try {
            init();
            Class.forName(config.driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Connection getCon() throws SQLException {
        return DriverManager.getConnection(config.url,config.username,config.password);
    }

      void close(AutoCloseable...acs){
        for (AutoCloseable ac : acs) {
            if (ac!=null) {
                try {
                    ac.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

BaseDao

public class BaseDao extends BaseConfig {
    private PreparedStatement getPst(Connection con,String  sql,Object...params) throws SQLException {
        PreparedStatement pst = con.prepareStatement(sql);
        if (params.length>0) {
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i+1,params[i]);
            }
        }
        return pst;
    }

    public Result exeNonQuery(String sql,Object...params){
        Connection con=null;
        PreparedStatement pst=null;
        try {
            con=getCon();
            pst=getPst(con,sql,params);
            pst.execute();
            return Result.succeed();
        } catch (SQLException e) {
            e.printStackTrace();
            return Result.fail();
        }finally {
            close(pst,con);
        }
    }

    public Result exeQuery(String sql,Object...params){
        Connection con=null;
        PreparedStatement pst=null;
        ResultSet rst = null;
        try {
            con=getCon();
            pst=getPst(con,sql,params);
            rst=pst.executeQuery();
            List<List<String>> table = new ArrayList<>();
            if (null!=rst&&rst.next()) {
              final int CC = rst.getMetaData().getColumnCount();
                do{
                    List<String> row = new ArrayList<>(CC);
                    for (int i = 1; i <=CC ; i++) {
                        row.add(rst.getObject(i).toString());
                    }
                    table.add(row);
                }while(rst.next());
            }
            return Result.succeed(table);
        } catch (SQLException e) {
            e.printStackTrace();
            return Result.fail();
        }finally {
            close(rst,pst,con);
        }
    }

    public String readSql(String...paths) throws IOException {
        String path = paths.length==0 ? "sql/sql.sql" :paths[0];
        StringBuilder builder = new StringBuilder();
        BufferedReader reader= new BufferedReader(new FileReader(path));
        String line = null;
        while (null != (line = reader.readLine())) {
            builder.append(line.trim()+" ");
        }
        return builder.toString();
    }
}

Result类

public abstract class Result<T> {
    private boolean err;
    private T data;

    public static Result fail(){
        return new Result(true) {
        };
    }
    public static <T> Result succeed(T...t){
        return new Result(false,t) {
        };
    }


    public Result(boolean err, T...data) {
        this.err = err;
        this.data = data.length>0 ? data[0]:null;
    }

    public boolean isErr() {
        return err;
    }

    public T getData() {
        return data;
    }
}

Test类

public class Test{
    public static void main( String[] args ) throws Exception {
        BaseDao dao = new BaseDao();
        StringBuilder sql = new StringBuilder();
        sql.append("");
        sql.append("");

        Result<List<List<String>>> tables = dao.exeQuery(dao.readSql());
        tables.getData().forEach(row->{
            row.forEach(cell->{
                System.out.print(cell+"\t");
            });
            System.out.println();
        });
    }
}

三、java连接hbase
代码如下:

public class HBASEClientDemo {
    @Test
    public void createTable() throws IOException {
        //1.获取hbase连接,配置
        //hbase.zookeeper.property.clientPort
        Configuration conf = HBaseConfiguration.create();
        
        //ATTENTION PLEASE!!!        
        //" IP_ADDRESS " 处,输入对应的虚机的IP地址,或者输入对应的虚机的主机名
        conf.set("hbase.zookeeper.quorum"," IP_ADDRESS ");
        //" 端口号 " 处,输入对应的端口号
        conf.set("hbase.zookeeper.property.clientPort"," 端口号 ");
        
        
        //2.创建连接
        Connection conn = ConnectionFactory.createConnection(conf);
        //3.创建admin
        Admin admin = conn.getAdmin();
        //4.创建表的相关信息,表名
        HTableDescriptor student = new HTableDescriptor(TableName.valueOf("student"));
        //5.添加列族信息
        student.addFamily(new HColumnDescriptor("info"));
        student.addFamily(new HColumnDescriptor("score"));
        //6.调用创建表的方法进行建表操作
        admin.createTable(student);
        //7.关闭连接
        conn.close();
    }

    @Test
    public void putData2Table() throws IOException {
        //1.配置
        Configuration conf = HBaseConfiguration.create();
        
        //ATTENTION PLEASE!!!       
        //" IP_ADDRESS " 处,输入对应的虚机的IP地址,或者输入对应的虚机的主机名
        conf.set("hbase.zookeeper.quorum"," IP_ADDRESS ");
        //" 端口号 " 处,输入对应的端口号
        conf.set("hbase.zookeeper.property.clientPort"," 端口号 ");
        
        
        //2.创建连接
        Connection conn = ConnectionFactory.createConnection(conf);
        //3.获取table
        Table student = conn.getTable(TableName.valueOf("student"));
        //4.往表中添加数据
        Put put = new Put(Bytes.toBytes("1001"));
        //5.添加列 info:name zhangsan
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("name"),Bytes.toBytes("zhangsan"));
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("gender"),Bytes.toBytes("male"));
        put.addColumn(Bytes.toBytes("info"),Bytes.toBytes("age"),Bytes.toBytes(10));
        //6.插入数据
        student.put(put);

        //7.关闭连接
        conn.close();
    }
    //读取数据
    @Test
    public void getDataFromTable() throws IOException {
        //1.配置
        Configuration conf = HBaseConfiguration.create();
      
        //ATTENTION PLEASE!!!        
        //" IP_ADDRESS " 处,输入对应的虚机的IP地址,或者输入对应的虚机的主机名
        conf.set("hbase.zookeeper.quorum"," IP_ADDRESS ");
        //" 端口号 " 处,输入对应的端口号
        conf.set("hbase.zookeeper.property.clientPort"," 端口号 ");
        
        
        //2.连接
        Connection conn = ConnectionFactory.createConnection(conf);
        //3.获取table
        Table student = conn.getTable(TableName.valueOf("student"));
        //4.读取数据,Get
        Get get = new Get(Bytes.toBytes("1001"));
        //5.获取结果
        Result result = student.get(get);

        //6.遍历
        Cell[] cells = result.rawCells();
        for (Cell cell : cells) {
            //获取具体的值
            System.out.println("rowkey:"+Bytes.toString(CellUtil.cloneRow(cell)));
            System.out.println("列族:"+Bytes.toString(CellUtil.cloneFamily(cell)));
            System.out.println("列名:"+Bytes.toString(CellUtil.cloneQualifier(cell)));
            System.out.println("value:"+Bytes.toString(CellUtil.cloneValue(cell)));
            System.out.println("------------------------------------");
        }
        conn.close();
    }
    //删除数据
    public void dropTable() throws IOException {
        //1.配置
        Configuration conf = HBaseConfiguration.create();
        
        //ATTENTION PLEASE!!!
        //" IP_ADDRESS " 处,输入对应的虚机的IP地址,或者输入对应的虚机的主机名
        conf.set("hbase.zookeeper.quorum"," IP_ADDRESS ");
        //" 端口号 " 处,输入对应的端口号
        conf.set("hbase.zookeeper.property.clientPort"," 端口号 ");
        
        
        //2.连接
        Connection conn = ConnectionFactory.createConnection(conf);
        //3.get admin
        Admin admin = conn.getAdmin();
        //4.禁用表
        admin.disableTable(TableName.valueOf("student"));
        //5.删除表
        admin.deleteTable(TableName.valueOf("student"));

        conn.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值