Java中JDBC的进阶——Druid和SpringJDBC的使用

Druid

什么是druid?

Druid是Alibaba(阿里巴巴)旗下开发的产品。
Druid不仅是一个数据库连接池,还包含一个ProxyDriver、一系列内置的JDBC组件库、一个SQL Parser。
支持所有JDBC兼容的数据库,包括Oracle、MySql、Derby、Postgresql、SQL Server、H2等。Druid提供了MySql、Oracle、Postgresql、SQL-92的SQL的完整支持,这是一个手写的高性能SQL Parser,支持Visitor模式,使得分析SQL的抽象语法树很方便。
Druid针对Oracle和MySql还做了特别优化。

使用Druid连接数据库的步骤
1.导入Druid和数据库连接的 jar包

在这里插入图片描述

2.封装properties文件

上篇文章已经说过了,本篇不再做陈述。

2.封装jdbc工具类
public class DruidTools {
    private static DataSource ds;
    static {
        try {
            Properties p= new Properties();
            //路径写自己文件的路径
            p.load(DruidTools.class.getClassLoader().getResourceAsStream("peizhi/druid.properties"));
            //此方法返回的是一个数据库连接池
            ds= DruidDataSourceFactory.createDataSource(p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取connection连接
    public static Connection getConnection() throws SQLException {
        //从池中抽取一个连接
        return ds.getConnection();
    }
    //关闭资源
    public static void close(Statement stmt,Connection conn){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //关闭资源 (重载)
    public static void close(Statement stmt, Connection conn, ResultSet res){
        if (stmt!=null){
            try {
                stmt.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (conn!=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (res!=null){
            try {
                res.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    //返回dataSource(用于spring jdbc)
    public static DataSource getDataSource(){
        return ds;
    }
}
使用SpringJDBC

直接上代码演示

public class jdbc {
     /* 第一步 导入对应的5个jar包
     第二步 创建jdbcTemplate对象,需要传入dataSource (自定义的DruidTools工具类)*/

    private JdbcTemplate template=new JdbcTemplate(DruidTools.getDataSource());

    /*
          第三步 : 常用方法  1.update() 返回int  用于增删改
                           2.query()执行查询语句 可以封装成自定义的对象 返回list<自定义>集合
                           3.queryFor Map/list/object() 用于查询语句 返回对应集合
                          注意:queryForMap()只能返回一条查询结果
                          下列演示代码中 User 是我自定义的类
    */
    @Test
    // update() 执行增删改的语句  其中 10 10001 分别对应两个?
    public void tese1(){
        String sql="update students set age=? where id=?";
        template.update(sql,10,10001);
    }
    @Test
    //注意 queryForMap 只能返回一条查询记录    若是多条使用 queryForList集合( 底层是封装多个map 存入list)
    public  void test02(){
        String sql="select * from students where id=?";
        Map<String, Object> stringObjectMap = template.queryForMap(sql, 10001);
    }
    @Test
    //将返回内容装入对象,使用匿名内部类的方式 new RowMapper<自定义>使用自定义来实现
    public void test03(){
        String sql="select * from students";
        List<User> query = template.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet resultSet, int i) throws SQLException {
                int id = resultSet.getInt("id");
                int age = resultSet.getInt("age");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                User user = new User(id, name, sex, age);
                return user;
            }
        });
        for (User user:query){
            System.out.println(user);
        }
    }
    @Test
    //将返回内容装入对象  使用官方内定的类  BeanPropertyRowMapper<自定义类>(类名.class) 此类实现了 RowMapper接口 底层使用反射机制原理
    public void test04(){
        String s = "select * from students";
        List<User> query = template.query(s, new BeanPropertyRowMapper<User>(User.class));
        for (User user:query){
            System.out.println(query);
        }
    }
    @Test
    //sql语句中返回内容有聚合函数(例如 avg()、sum()、count() )的情况
    public void test05(){
        String sql = "select count(id) from students";
        Long count = template.queryForObject(sql, long.class);//其中 count聚合函数返回的类型为long,所以指定返回类型
        System.out.println(count);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值