数据库连接池

11 篇文章 0 订阅
2 篇文章 0 订阅

学习内容:

  1.数据库连接池

(餐厅服务员举例讲解)

      (1)概念:其实就是一个容器(集合),存放数据库连接的容器。

                    当系统初始化好后,容器被创建,容器中会申请一些连接对象,当用户来访问数据库的时,从容器中获取对象,用户访问完后,将连接对象归还给容器(连接池)

      (2)好处:

                  a:节约资源

                  b.用户访问高效

     (3)实现

               1.标准接口: javax.sql      接口 DataSource,

                           一个连接到这个DataSource对象所代表的数据源的工厂。作为 DriverManager 工具的替代项,DataSource 对象是获取连接的首选方法。实现 DataSource 接口的对象通常在基于 JavaTM Naming and Directory Interface (JNDI) API 的命名服务中注册。

                         DataSource接口又驱动程序供应商实现。三种实现类  ;

                                    1. 基本实现 - 生成标准的 Connection 对象

                       a:方法:

                                * 获取连接:getConnection()

                                * 归还连接:Connection.close();如果连接对象Connection是从连接池中获取的,那么调用Connection.close()方法,则不会关闭连接,而是归还连接。

              2.一般自己不去实现它,由数据库厂商来实现

                       a.C3P0:数据库连接池技术

                       b.Druid:数据库连接池实现技术,由阿里巴巴提供的,(全世界最好的数据库连接池技术之一)

 

     (4)C3P0数据库连接池技术

              * 步骤:

                      1.导入jar包 (两个)c3p0-0.9.5.2.jar    mchange-commons-java-0.2.12.jar 

                                不要忘记数据库的驱动jar包 mysql-connector-java-5.1.48-bin.jar

                       2.定义配置文件:

                                 * 名称:   c3p0.properties 或者 c3p0-config.xml

                                 * 路径 :直接将文件放在src目录下即可(at the top level of an application's classpath)。  

                       3.创建核心对象,数据库连接池对象:ComboPooledDataSource     (类)

                       4.获取连接:getConnection()

         c3p0连接池代码展示

public class C3P0Demo1 {
    public static void main(String[] args) {
        DataSource ds = null;
        try {
            //1.创建数据库连接池对象
            ds = new ComboPooledDataSource();
            //2.获取连接对象
            Connection conn = ds.getConnection();
            //3.打印
            System.out.println(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
/*
 * c3p0演示
 * */
public class C3P0Demo02 {
    public static void main(String[] args) throws SQLException {
        //1.获取DataSource,使用默认配置
        DataSource ds = new ComboPooledDataSource();


        //2.获取连接
        for (int i=0;i < 11; i++) {
            //只要十个连接池对象,当访问第十一个时,就会出现报错现象
            Connection conn = ds.getConnection();
            System.out.println(conn);
            //解决方法
            if (i==5){
                conn.close();//归还连接对象到连接池中,让后边的继续使用
                //释放某个连接池对象,如此以来,就
            }
        }

    }
    @Test
    public void testNameConfig() throws SQLException {
        //1.1获取DataSource ,使用指定名称配置
        DataSource ds = new ComboPooledDataSource("otherc3p0");
        //2.获取连接
        for (int i=0;i < 11; i++) {
            //只要十个连接池对象,当访问第十一个时,就会出现报错现象
            Connection conn = ds.getConnection();
            System.out.println(conn);
            //解决方法
            if (i==5){
                conn.close();//归还连接对象到连接池中,让后边的继续使用
                //释放某个连接池对象,如此以来,就
            }
        }
    }
}

     

   druid代码展示:

                   工具类(包含静态代码块,主要加载配置文件)

public class JDBCUtils {
    //1.定义一个成员变量
    private static DataSource ds;
    static {

        try {
            //1.加载配置文件
            Properties props = new Properties();
            props.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //2.获取DataSource
             ds = DruidDataSourceFactory.createDataSource(props);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /*
    * 获取连接
    * */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    /*
    * 释放资源
    * */
    public static void close(Statement stmt,Connection conn){
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close(); //归还连接对象
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(Statement stmt,Connection conn,ResultSet rs){
        try {
            if (stmt != null) {
                stmt.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn != null) {
                conn.close(); //归还连接对象
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }try {
            if (rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /*
    *获取连接池的方法
    * */
    public static DataSource getDataSource() {
        return ds;
        }
}

         连接池代码示例

/*
* 使用新的工具类
*
* */
public class DrudiDemo02 {
    public static void main(String[] args) {
        /*
        * 完成添加操作。给user表添加一条记录
        * */
        Connection conn = null;
        PreparedStatement pstmt = null;

        try {
            //1.获取连接
            conn = JDBCUtils.getConnection();
            //2.定义sql语句
            String sql = "insert into event values(null, ? , ?)";
            //3.获取pstmt 对象
            pstmt = conn.prepareStatement(sql);
            //4.给?赋值
            pstmt.setString(1,"wangwu");
            pstmt.setString(2,"456");
            //5.执行sql语句
            int count = pstmt.executeUpdate();
            System.out.println(count);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6.释放资源
            JDBCUtils.close(pstmt,conn);
        }

    }
}

 2.Spring JDBC :JDBC Template

        *Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发

         *步骤:

                  1.导入jar包

                   2.创建对象,JdbcTemplate对象。依赖于数据源DataSource

                              *JdbcTemplate template  = new JdbcTemplate(ds)

                   3.调用JdbcTemplate的方法来完成CRUD操作

                            *update():执行DML语句。增、删、改语句

                            * queryForMap():查询结果将结果集封装为map集合,将列名作为key,将值作为value 将这条记录封装为一个map集合
                         
                             * queryForList():查询结果将结果集封装为list集合
                                                * 注意:将每一条记录封装为一个Map集合,再将Map集合装载到List集合中
                            * query():查询结果,将结果封装为JavaBean对象
                            * query的参数:RowMapper
                                            * 一般我们使用BeanPropertyRowMapper实现类。可以完成数据到JavaBean的自动封装
                             * new BeanPropertyRowMapper<类型>(类型.class)
                              * queryForObject:查询结果,将结果封装为对象
                                          * 一般用于聚合函数的查询

                                          * 注意:这个方法查询的结果集长度只能是1

                    4. 练习:
                          * 需求:
                                 1. 修改1号数据的 salary 为 10000
                                 2. 添加一条记录
                                 3. 删除刚才添加的记录
                                 4. 查询id为1的记录,将其封装为Map集合
                                 5. 查询所有记录,将其封装为List
                                 6. 查询所有记录,将其封装为Emp对象的List集合
                                 7. 查询总记录数

           代码实现:

public class JdbcTemplateDemo02 {
    /*
    * 定义成员变量
    * */
    //1.获取JdbcTemplate连接对象
    JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
    //Junit单元测试,可以让方法独立执行
    /*
    *  1.修改2号数据的 price 为4000;
    * */
    @Test
    public void test1(){
        //1.获取 JdbcTemplate连接对象
        //JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
        //2.定义sql语句
        String sql = "update product set price = 4000 where id = 2";
        //
        int count = jdbcTemplate.update(sql);
        if (count == 1) {
            System.out.println("修改成功");
        } else {
            System.out.println("修改失败");
        }
    }
    /*
    *  2.添加一条记录
    * */
    @Test
    public void test2(){

        //2.定义sql语句
        String sql = "insert into product(pname,price) values(?,?)";
        int count = jdbcTemplate.update(sql,"甜甜圈","50");
        if (count==1) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }
    /*
    *  3.删除刚才添加的记录
    * */
    @Test
    public void test3(){
        //定义sql语句
        String sql = "delete from product where pname=? ";
        int count = jdbcTemplate.update(sql, "甜甜圈");
        if (count==1) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }
    /*
    *  4.查询id为1的记录,将其封装为map集合
    *   注意:这个方法查询的结果集只能是1
    * */
    @Test
    public void test4(){
        //1.定义sql语句
        String sql = "select * from product where id = ? ";
        Map<String, Object> stringObjectMap = jdbcTemplate.queryForMap(sql,1);
        System.out.println(stringObjectMap);

    }
    /*
        5.查询所有记录,将其封装为List
    * */
    @Test
    public void test5(){
        String sql = "select * from product";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
        for (Map<String,Object> stringObjectMap:list){
            System.out.println(stringObjectMap);
        }
    }
    /*
    * 6.查询所有记录,将其封装为Product对象的list集合
    * */
    @Test
    public void test6(){
        String sql = "select * from product";
        List<Product> list = jdbcTemplate.query(sql, new RowMapper<Product>() {
            @Override
            public Product mapRow(ResultSet rs, int i) throws SQLException {
                Product product = new Product();
                int id = rs.getInt("id");
                String pname = rs.getString("pname");
                String price = rs.getString("price");
                String catagory_id = rs.getString("catagory_id");

                product.setId(id);
                product.setPname(pname);
                product.setPrice(price);
                product.setCatagory_id(catagory_id);

                return product;
            }
        });
        for (Product product : list){
            System.out.println(product);
        }
    }
    @Test
    public void test6_2(){
        String sql = "select * from product";
        List<Product> list = jdbcTemplate.query(sql,new BeanPropertyRowMapper<Product>(Product.class));
        for (Product product : list){
            System.out.println(product);
        }

    }
    /*
    * 7. 查询总记录数
    * */
    @Test
    public void test7(){

        String sql = "select count(id) from product";
        Long total = jdbcTemplate.queryForObject(sql,Long.class);
        /*
        * queryForObject(sql,Long.class)
        * 一般用来执行一些聚合函数
        * */
        System.out.println(total);

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Janson666

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值