JDBC连接池

JDBC连接池

JDBC提供的连接池规范 DataSource

连接池 - 存储连接
好处:
– 在连接池中的连接,在连接池初始化时就已经创建好(在使用连接的时候, 就可以快速获得连接对象
– 连接使用完成后, 可以将连接归还给连接池, 让连接重复使用

C3P0

使用c3p0第三方连接池步骤:
– 导入jar包
– 编写配置文件 c3p0-config.xml/c3p0.properties
位置: 必须在类路径的根目录中 -> src中
– 创建连接池对象 ComboPooledDataSource

        // 使用配置文件 c3p0-config.xml 来指定连接池的参数/属性配置
        // 在使用ComboPooledDataSource无参构造器创建这个连接池对象时, 会自动去读取c3p0-config.xml文件内容
        
        // 读取完c3p0-config.xml 后, 使用的是default-config里的配置信息
        DataSource dataSource = new ComboPooledDataSource();
        
        // 有参构造器, 传入一个name, 使用的就是named-config="otherc3p0"
        DataSource dataSource1 = new ComboPooledDataSource("otherc3p0");
        
        // 从连接池中获得连接
        Connection conn = dataSource.getConnection();
<c3p0-config>
    <!-- 使用默认的配置读取连接池对象 -->
    <default-config>
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///db_day01</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <!-- 连接池参数 -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">10</property>
        <property name="checkoutTimeout">3000</property>
    </default-config>

    <named-config name="otherc3p0">
        <!--  连接参数 -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///db_day01</property>
        <property name="user">root</property>
        <property name="password">root</property>

        <!-- 连接池参数 -->
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">8</property>
        <property name="checkoutTimeout">1000</property>
    </named-config>
</c3p0-config>

Druid

使用Druid连接池步骤
– 导入jar包
– 编写配置文件
位置和名字都随意
– 通过工厂创建连接池对象
DruidDataSourceFactory.createDataSource(Properties)

        // 创建一个属性集 Properties
        Properties pros = new Properties();
        pros.load(Demo01.class.getResourceAsStream("druid.properties"));
        // Druid连接池提供了一个获得DataSource的工厂类
        DataSource dataSource = DruidDataSourceFactory.createDataSource(pros);
        Connection conn = dataSource.getConnection();

封装Druid

public class DruidUtils {
    private static DataSource dataSource;

    static {
        Properties pro = new Properties();
        try {
            pro.load(DruidUtils.class.getResourceAsStream("druid.properties"));
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static DataSource getDataSource() {
        return dataSource;
    }
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}

JdbcTemplate
使用JdbcTemplate步骤
– 导包
– 创建JdbcTemplate对象
– 用JdbcTemplate操作数据库

创建JdbcTemplate对象

JdbcTemplate template = new JdbcTemplate(DruidUtils.getDataSource());

执行DML的方法

        // 插入
        String sql = "insert into emp(empno,ename,job,sal,comm,hiredate) values(?,?,?,?,?,?)";
        template.update(sql,8000,"jack","CLERK",800,0,"2020-08-14");
        // 修改
        String sql = "update emp set ename=?,sal=?,job=?,comm=?,hiredate=? where empno=?";
        template.update(sql,"jack james",800,"CLERK",100,"2020-08-14",8000);
        // 删除
        String sql = "delete from emp where empno = ?";
        template.update(sql,8000);

执行DQL的方法

        // 只能处理一条结果集(将列名作为key, 列中的数据作为value封装到map中)
        String sql = "select * from emp where empno=?";
        Map<String, Object> map = template.queryForMap(sql, 7369);
        // {empno=7369, ename=SMITH, job=CLERK, mgr=7902, hiredate=1980-12-17, sal=800, comm=null, deptno=20}
        System.out.println(map);
        // 将查询出来的结果集,每一行封装为一个map, 再将这个map封装到list中
        String sql = "select * from emp";
        List<Map<String, Object>> list = template.queryForList(sql);
        // 查询单列数据,并且将这一列数据, 转换成Class对应的类型对象
        String sql = "select count(*) from emp";
        Long count = template.queryForObject(sql, Long.class);
        System.out.println(count);
        String sql = "select * from emp";
        /**
         * RowMapper: 将结果集进行封装处理, 通过mapRow进行处理
         * query 得到的结果集ResultSet, 并且遍历结果集, 
         *  然后调用RowMapper中的mapRow方法对每一行结果进行封装处理
         */
        List<Emp> list = template.query(sql, new RowMapper<Emp>() {
            @Override
            /**
             * rs: 当前指向的那一行结果数据 rs.getString/Int..
             * i: 当前遍历的次数 - 了解
             * @return 将一行数据封装得到的对象
             */
            public Emp mapRow(ResultSet rs, int i) throws SQLException {
                Emp emp = new Emp();
                emp.setEmpno(rs.getInt("empno"));
                emp.setEname(rs.getString("ename"));
                emp.setSal(rs.getDouble("sal"));
                emp.setJob(rs.getString("job"));
                emp.setComm(rs.getDouble("comm"));
                emp.setHiredate(rs.getDate("hiredate"));
                return emp;
            }
        });

注:实体类的属性名 和 表的字段名一致

        // RowMapper实现类:BeanPropertyRowMapper
        List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));

补充

通过连接池获得的连接与通过JDBC方式获得的连接的区别

通过连接池获得的连接关闭后, 连接对象返回给连接池, 并且引用设置为null
通过JDBC获得的连接关闭后, 连接对象还在, 但是状态是"已关闭", 不能再使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值