zoukankan      html  css  js  c++  java
  • java学习笔记之数据库连接池(DBCP和C3P0)

    数据库连接池(DBCP和C3P0)

    一.数据库连接池的概念

      数据库连接池可以理解为是存放多个数据库连接的集合。

      作用;解决建立数据库连接耗费很多资源和时间问题,提高性能

      Java为数据库连接池提供了公共的接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。这样应用程序可以方便的切换不同厂商的连接池!

      连接池图解:
     

     二..DBCP连接池:

      1.简单介绍:

        dbcp是apache组织的开源的连接池

      2.使用步骤:

        ①添加jar包 commons-dbcp-1.4.jar  commons-pool-1.5.6.jar

        ②,编写配置文件(四大信息)

          配置文件名以   .properties结尾

          最好放在src目录下

          配置文件信息如下:

    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/day05db
    username=root
    password=root

        ③编写连接池工具类

     1 import java.sql.Connection;
     2 import java.sql.ResultSet;
     3 import java.sql.SQLException;
     4 import java.sql.Statement;
     5 import java.util.Properties;
     6 
     7 import javax.sql.DataSource;
     8 
     9 import org.apache.commons.dbcp.BasicDataSourceFactory;
    10 /*
    11  * javax.sql.DataSource接口
    12  *    DBCP连接池实现类:
    13  *      BasicDataSource
    14  *      BasicDataSourceFactory
    15  * 
    16  * 连接池的创建步骤 :
    17  *  1:创建一个空的连接池
    18  *     BasicDataSource dataSource = new  BasicDataSource();
    19  *  2:给这个连接池设置四大信息--->连接池会自动的向池子中存放连接 (默认一般是10个)
    20  *    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    21  *    dataSource.setUrl("jdbc:mysql://localhost:3306/day04db");
    22  *    dataSource.setUserName("root");
    23  *    dataSource.setPassword("123");
    24  *    
    25  *  3:封装一个方法,对外提供一个连接池中连接 
    26  *     getConntion();
    27  */
    28 public class MyDBCPUtils {
    29     private static DataSource dataSource=null;
    30     //创建一个空的连接池
    31     static{
    32         Properties properties=new Properties();
    33         try {
    34             
    35             properties.load(MyDBCPUtils.class.getClassLoader().getResourceAsStream("dbcp.properties"));
    36             /*MyDBCPUtils.class.getClassLoader().getResourceAsStream("dbcp.properties")
    37              * 方法会自动的去bin目录中找配置文件夹
    38              */
    39             /*
    40              * 该方法会做两件事情:
    41              *  1:自动从Properties集合中获取四大信息
    42              *  2: 创建一个有连接的连接池
    43              */
    44             dataSource=BasicDataSourceFactory.createDataSource(properties);
    45         } catch (Exception e) {
    46             // TODO Auto-generated catch block
    47             e.printStackTrace();
    48         }
    49         
    50     }
    51     /**
    52      * 创建一个静态方法 ,可以让外界获取连接对象
    53      * @return  Connection 
    54      * @throws Exception
    55      */
    56     public static Connection  getConnection() throws Exception{
    57         return dataSource.getConnection();
    58     }
    59     /**
    60      * 
    61      * @param rs 结果集对象,没有写null
    62      * @param stat  sql执行平台对象
    63      * @param conn  数据库连接对象
    64      */
    65     public static void closeAll(ResultSet rs,Statement stat,Connection conn){
    66         
    67         if(rs!=null){
    68             try {
    69                 rs.close();
    70             } catch (SQLException e) {
    71                 // TODO Auto-generated catch block
    72                 e.printStackTrace();
    73             }
    74         }
    75         if(stat!=null){
    76             try {
    77                 stat.close();
    78             } catch (SQLException e) {
    79                 // TODO Auto-generated catch block
    80                 e.printStackTrace();
    81             }
    82         }
    83         
    84         //这里这个close不是关流释放资源,而是重写方法,将连接放回连接池
    85         if(conn!=null){
    86             try {
    87                 conn.close();
    88             } catch (SQLException e) {
    89                 // TODO Auto-generated catch block
    90                 e.printStackTrace();
    91             }
    92         }
    93     }
    94 
    95 }

      ④使用编写的工具类(简单demo)

     1 import java.sql.Connection;
     2 import java.sql.PreparedStatement;
     3 import java.sql.ResultSet;
     4 
     5 public class Test01 {
     6     public static void main(String[] args)throws  Exception{
     7         //获得连接
     8         Connection conn = MyDBCPUtils.getConnection();
     9         
    10         //获得sql语句的执行平台
    11         PreparedStatement stat = conn.prepareStatement("select * from student");
    12         //获得结果集
    13         ResultSet result = stat.executeQuery();
    14         //处理结果集
    15         
    16         while(result.next()){
    17             System.out.println(result.getInt("stu_id"));
    18         }
    19         //释放资源
    20         MyDBCPUtils.closeAll(result, stat, conn);
    21         
    22     }
    23 
    24 }

    三.C3P0连接池

      1.简单介绍

        C3P0开源免费的连接池!目前使用它的开源项目有:SpringHibernate等。使用第三方工具需要导入jar包,c3p0使用时还需要添加配置文件 c3p0-config.xml

      2使用步骤:

        ①:导入jar包

        ②:编写配置文件

            文件类型:xml

            文件名必须是 c3p0-config.xml,放在src中

            简单的文件demo:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 
     3 <!--
     4             dataSource.setDriverClass("com.mysql.jdbc.Driver");
     5             dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/day05db");
     6             dataSource.setUser("root");
     7             dataSource.setPassword("123");
     8 
     9       1:获取name属性:driverClass
    10       2:进行字符串拼接:setDriverClass
    11       3: 反射setDriverClass()
    12       4: 调用setDriverClass()给变量赋值:com.mysql.jdbc.Driver
    13  -->
    14 <c3p0-config> 
    15     <default-config>
    16          <property name="driverClass">com.mysql.jdbc.Driver</property>
    17          <property name="jdbcUrl">jdbc:mysql://localhost:3306/day05db</property>
    18          <property name="user">root</property>
    19          <property name="password">123</property>
    20     </default-config>
    21 </c3p0-config>

      ③编写连接池使用工具类

      

     1 /*
     2  * javax.sql.DataSource接口
     3  *    实现类:ComboPooledDataSource
     4  *    
     5  * 创建连接池:
     6  *   1:创建一个空的连接池
     7  *      ComboPooledDataSource dataSource = new ComboPooledDataSource();
     8  *   2: 设置四大信息--->连接池会自动的存放连接
     9  *     dataSource.setXxx("");
    10  *     dataSource.setXxx("");
    11  *     dataSource.setXxx("");
    12  *     dataSource.setXxx("");
    13  */
    14 
    15 public class MyC3P0Utils {
    16     /*
    17      * 1:该对象在创建的时候会自动的检测是否有c3p0-config.xml
    18      * 2: 如果没有c3p0-config.xml
    19      *    你需要手动的设置四大信息
    20      * 3: 如果有c3p0-config.xml
    21      *    1:该对象在创建的时候会自动的解析xml文件
    22      *    2:获取四大信息
    23      *    3: 创建连接池,并向连接池中存放连接池
    24      */
    25     private static DataSource dataSource = new ComboPooledDataSource();
    26 
    27     //封装一个方法,让别人能够获取连接池中的连接
    28     public static Connection getConnetion()throws Exception{
    29         
    30         return dataSource.getConnection();
    31     }
    32     
    33     public static void closeAll(ResultSet rs, Statement stat, Connection conn) {
    34         if (rs != null) {
    35             try {
    36                 rs.close();
    37             } catch (SQLException e) {
    38                 e.printStackTrace();
    39             }
    40         }
    41         if (stat != null) {
    42             try {
    43                 stat.close();
    44             } catch (SQLException e) {
    45                 e.printStackTrace();
    46             }
    47         }
    48         if (conn != null) {
    49             try {
    50                 conn.close();// 连接池已经重写类该方法,该方法是将连接重新放回到连接池
    51             } catch (SQLException e) {
    52                 e.printStackTrace();
    53             }
    54         }
    55     }
    56 }

      ④使用工具类

     1 import java.sql.Connection;
     2 import java.sql.PreparedStatement;
     3 
     4 public class TestDemo01 {
     5     public static void main(String[] args) throws Exception {
     6         //1:获取连接
     7          Connection conn = MyC3P0Utils.getConnetion();
     8         //2:执行sql
     9         PreparedStatement stat = conn.prepareStatement("delete from category where cid = ?");
    10         stat.setObject(1, 2);
    11         int rows = stat.executeUpdate();
    12         
    13         //3:处理结果
    14         if(rows > 0){
    15             System.out.println("删除成功");
    16         }else{
    17             System.out.println("删除失败");
    18         }
    19         
    20         //4: 释放资源
    21         MyC3P0Utils.closeAll(null, stat, conn);
    22     }
    23 }
  • 相关阅读:
    SQLServer性能杀手
    SqlServer内存瓶颈分析SQLServer:Buffer Manager
    HTML5变化 (一)
    对于using嵌套的改进
    String.IsNullOrEmpty()和String.IsNullOrWhiteSpace()
    querySelector & querySelectorAll
    Action<T> 委托
    Func<T, TResult>
    SL4.背景图片拖动
    JavaScript日志
  • 原文地址:https://www.cnblogs.com/xuzhaocai/p/8186506.html
Copyright © 2011-2022 走看看