数据库连接池(数据源)

1、数据库连接池

数据库开启连接 – 执行代码 – 释放连接
开启连接和释放连接十分浪费系统资源
池化技术:准备一些预先的资源,过来就连接预先准备好的

最小连接数:10
最大连接数:15业务最高承载上限
多于最大连接数的排队等待
等待超时:100ms

连接池,实现一个接口DataSource

开源数据源实现
dbcp
c3p0
Durid:阿里巴巴

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

1.1、DBCP

需要用到的jar包
在这里插入图片描述
创建DBCP配置文件

#连接设置
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&characterEncoding=utf8&useSSL=true&serverTimezone-GMT%2B8
username=root
password=root

#!-- 初始化连接 --
initialSize=10

#最大连接数量
maxActive=50

#!-- 最大空闲连接 --
maxIdle=20

#!-- 最小空闲连接 --
minIdle=5

#!-- 超时等待时间以毫秒为单位 6000毫秒/100等于60秒 --
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:【属性名=property;】
#注意:user 与 password 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=UTF8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED

创建DBCP工具包

package com.jialidun.datasource.utils;



import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils_DBCP{

        private static DataSource dataSource = null;



        static {

            try {

                InputStream in =
                        JdbcUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
                Properties properties = new Properties();
                properties.load(in);

                //创建数据源 工厂模式--->创建
                dataSource = BasicDataSourceFactory.createDataSource(properties);


            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        //获取连接
    public static Connection getConnection() throws SQLException {
            return dataSource.getConnection();//从数据源获取连接
    }



        //释放连接资源
        public static void close(Connection connection, Statement statement, ResultSet resultSet){
            if(resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(statement!=null){
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(connection!=null){
                try {
                    connection.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

}



测试添加用户

package com.jialidun.datasource.test;

import com.jialidun.datasource.utils.JdbcUtils_DBCP;
import com.jialidun.utils.JdbcUtils;

import java.sql.*;

public class TestDbcp {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement statement = null;
        String sql = null;

        try {
            //获取连接
            connection = JdbcUtils_DBCP.getConnection();



            sql = "insert into users(id,`NAME`,`PASSWORD`,`email`,`birthday`) values(?,?,?,?,?)";

            //获取statement传输器
            statement = connection.prepareStatement(sql);
            statement.setInt(1,4);
            statement.setString(2,"ragar");
            statement.setString(3,"rygar123");
            statement.setString(4,"rygar_h@163.com");
            statement.setDate(5,new Date(new java.util.Date().getTime()));

            int num = statement.executeUpdate();

            if(num > 0){
                System.out.println("添加用户成功!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放连接
            JdbcUtils_DBCP.close(connection,statement,null);


        }



    }
}

1.2、C3P0

需要的jar包如下:
在这里插入图片描述
在这里插入图片描述
c3p0配置文件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.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbcstudy?userUnicode=true&amp;characterEncoding=utf8&amp;uesSSL=true&amp;serverTimezone=UTC</property>
        <property name="user"> root </property>
        <property name="password">root</property>

        <property name="acquireIncrement"> 5 </property>
        <property name="initialPoolSize"> 10 </property>
        <property name="minPoolSize"> 5 </property>
        <property name="maxPoolSize">20</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/jdbcstudy?userUnicode=true&amp;characterEncoding=utf8&amp;uesSSL=true&amp;serverTimezone=UTC</property>
        <property name="user"> root </property>
        <property name="password">root</property>

        <property name="acquireIncrement"> 5 </property>
        <property name="initialPoolSize"> 10 </property>
        <property name="minPoolSize"> 5 </property>
        <property name="maxPoolSize">20</property>
    </named-config>
        </c3p0-config>

xml文件中的一些特殊符号
创建c3p0工具包

package com.jialidun.datasource.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class JdbcUtils_C3P0 {
    private static ComboPooledDataSource dataSource = null;



    static {

        try {

            //会自动读取xml文件里匹配的内容

            //创建数据源 工厂模式--->创建
            //dataSource = new ComboPooledDataSource("MySQL");//配置name = MySQL

            dataSource = new ComboPooledDataSource();

            //代码实现配置
//            dataSource.setJdbcUrl();
//            dataSource.setUser();
//            dataSource.setPassword();
//            dataSource.setMinPoolSize();
//            dataSource.setMaxPoolSize();
//            dataSource.setMaxIdleTime();
//            ...



        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //获取连接
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();//从数据源获取连接
    }



    //释放连接资源
    public static void close(Connection connection, Statement statement, ResultSet resultSet){
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
}

测试添加用户

package com.jialidun.datasource.test;

import com.jialidun.datasource.utils.JdbcUtils_C3P0;
import com.jialidun.datasource.utils.JdbcUtils_DBCP;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TestC3p0 {
    public static void main(String[] args) {

        Connection connection = null;
        PreparedStatement statement = null;
        String sql = null;

        try {
            //获取连接
            connection = JdbcUtils_C3P0.getConnection();



            sql = "insert into users(id,`NAME`,`PASSWORD`,`email`,`birthday`) values(?,?,?,?,?)";

            //获取statement传输器
            statement = connection.prepareStatement(sql);
            statement.setInt(1,5);
            statement.setString(2,"黑旋风李逵");
            statement.setString(3,"likui666");
            statement.setString(4,"likui@qq.com");
            statement.setDate(5,new Date(new java.util.Date().getTime()));

            int num = statement.executeUpdate();

            if(num > 0){
                System.out.println("添加用户成功!");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            //释放连接
            JdbcUtils_C3P0.close(connection,statement,null);


        }




    }
}

结论
无论使用什么数据源,本质还是一样的,DataSource接口不会变,方法就不会变。

Druid

Apache
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

RYGAR

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

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

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

打赏作者

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

抵扣说明:

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

余额充值