数据库连接池

数据库连接池

  • 数据库连接 —- 执行完毕 —- 释放

    连接 — 释放 十分浪费系统资源

    池化技术: 准备一些预先的资源,过来就连接预先准备好的

    ——— 开门 —- 业务员: 等待 — 服务 —

    常用连接数:10个

    最小连接数:5个

    最大连接数:15 业务最高承载上限

    超过等待排队

    等待超时:100ms

    编写连接池 实现 DataSource 接口

  • 开源数据源实现

    DBCP

    C3P0

    Druid: 阿里巴巴

    使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码

  • DBCP

    需要的jar包
    commons-dbcp-1.4 :https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp
    commons-pool-1.6 :https://mvnrepository.com/artifact/commons-pool/commons-pool

    • 创建dbcpconfig.properties配置文件

      #连接设置
      driverClassName=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true
      username=root
      password=root
      #<!-- 初始化连接 -->
      initialSize=10
      #最大连接数量
      maxActive=50
      #<!-- 最大空闲连接 -->
      maxIdle=20
      #<!-- 最小空闲连接 -->
      minIdle=5
      #<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
      maxWait=60000
      #JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
      #注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
      connectionProperties=useUnicode=true;
      characterEncoding=utf8
      #指定由连接池所创建的连接的自动提交(auto-commit)状态。
      defaultAutoCommit=true
      #driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
      #可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
      defaultTransactionIsolation=READ_UNCOMMITTED
      
      • 通过DBCP封装连接数据库的方法:

        public class jdbcUtils_dbcp {
            private static DataSource dataSource = null;
            static{
                try{
                    InputStream in = jdbcUtils.class.getResourceAsStream("/dbcpconfig.properties");
                    Properties properties = new Properties();
                    properties.load(in);
                    // 创建数据源  工厂模式 ----> 创建
                    DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //获取连接
            public static Connection getConnection() throws SQLException{
                return dataSource.getConnection();   // 从数据源中获取连接
            }
            // 释放连接
            public static void release(Connection connection, PreparedStatement ps, ResultSet rs) {
                try {
                    if (rs != null) {
                        rs.close();
                    }
                    if (ps != null) {
                        ps.close();
                    }
                    if (connection != null) {
                        connection.close();
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        
      • 测试方法

        public class Test01 {
            public static void main(String[] args) throws SQLException {
                Connection conn = null;
                PreparedStatement st = null;
                ResultSet rs = null;
                try {
                    conn = jdbcUtils_dbcp.getCollection(); //获取连接
                    String sql = "update users set `name` = ? where id = ?";
                    st = conn.prepareStatement(sql);
                    //手动赋值参数
                    st.setString(1,"xon");
                    st.setInt(2,1);
                    //执行
                    int i = st.executeUpdate();
                    if(i>0){
                        System.out.println("修改成功");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }finally {
                    jdbcUtils_dbcp.release(conn,st,rs);
                }
            }
        }
        
  • C3P0数据库连接池

  • 导入c3p0的包

    • c3p0-0.9.5.5.jar 和 mchange-commons-java-0.2.19.jar
  • 在项目src目录下创建c3p0-config.xml配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <c3p0-config>
    <!--    c3p0的缺省设置
            如果在代码中 ComboPooledDataSource ds = new ComboPooledDataSource() 这样表示的使用c3p0的默认设置
    -->
        <default-config>
            <property name="driverClass">com.mysql.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc</property>
            <property name="user">root</property>
            <property name="password">java</property>
            <property name="acquireIncrement">5</property>
            <property name="initialPoolSize">10</property>
            <property name="maxPoolSize">20</property>
            <property name="minPoolSize">5</property>
        </default-config>
        <!--    c3p0的命名设置
               如果在代码中 ComboPooledDataSource ds = new ComboPooledDataSource("mysql") 这样表示的使用c3p0的命名设置
    -->
        <named-config name="mysql">
            <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
            <property name="jdbcUrl">jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=true</property>
            <property name="user">root</property>
            <property name="password">root</property>
            <property name="acquireIncrement">5</property>
            <property name="initialPoolSize">10</property>
            <property name="maxPoolSize">20</property>
            <property name="minPoolSize">5</property>
        </named-config>
    </c3p0-config>
    
    • 通过c3p0封装连接数据库的方法

      public class JdbcUtil_c3p0 {
          private static ComboPooledDataSource dataSource = null;
          static{
              try {
                  dataSource = new ComboPooledDataSource("mysql");
              }catch (Exception e){
                  e.printStackTrace();
              }
          }
          public static Connection getConnection() throws SQLException {
             return dataSource.getConnection();
          }
          public static void closeConnection(Connection connection){
              try {
                  connection.close();
              } catch (SQLException throwables) {
                  throwables.printStackTrace();
              }
          }
      }
      
无论使用什么数据源,本质还是一样的,DataSource接口不会变,方法就不会变
posted @ 2021-05-16 20:45  saxon宋  阅读(45)  评论(0)    收藏  举报