首页 > 数据库 >数据库连接池的使用方法

数据库连接池的使用方法

时间:2022-12-01 13:46:56浏览次数:30  
标签:数据库 连接 connection comboPooledDataSource 方法 properties 连接池

数据库连接池概述

  基本介绍:

    1、预先在缓冲区防止一定数量的连接,当需要建立连接时,只需要在“缓冲区”中取出一个,使用完毕之后放回去。

    2、数据库连接池负责分配、管理和释放数据库的连接,它允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个连接。

    3、当应用程序想连接池的请求连接超过最大数量时,这些请求将被加入到等待队列中

 

C3P0数据库连接池

    速度相对较慢,稳定性还不错(hibernate、spring)

//方式一:在程序当中指定相关的参数user、url、password
    @Test
    public void testC3P0_01() throws IOException, PropertyVetoException, SQLException {
        //1、创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

        //2、通过配置文件mysql.properties 获取相关的连接信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //读取相关的属性值
        String user = properties.get("user").toString();
        String password = properties.get("password").toString();
        String url = properties.get("url").toString();
        String driver = properties.get("drive").toString();

        //给comboPooledDataSource 设置相关的参数
        //注意:连接管理是由 comboPooledDataSource 来进行管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        //最大连接数
        comboPooledDataSource.setMaxPoolSize(10);
        Connection connection = null;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            //这个方法就是从DataSource接口拿到连接
            connection = comboPooledDataSource.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0 5000连接mysql耗时:" + (end - start));
        //System.out.println("连接成功:" + connection);
    }
    //第二种方式:使用配置文件模板来完成
    //1、将c3p0提供的c3p0.config.xml 宝贝到src目录下
    //2、该文件指定连接数据库和连接池的相关参数
    @Test
    public void testC3P0_02() throws SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("db_edu");
        Connection connection = null;
        long satrt = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            connection = comboPooledDataSource.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - satrt));

    }
<!--   c3p0-config.xml配置文件 放置到项目的src目录下面 -->
<!--   数据源名称代表连接池     -->
<?xml version="1.0" encoding="utf-8"?>
<c3p0-config>
    <default-config>
        <!--   数据源名称代表连接池     -->
        <name-config name="db_edu" />
        <!--   数据库的连接地址    -->
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/db01</property>
        <!--   驱动类     -->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <!--   用户名     -->
        <property name="user">root</property>
        <!--   密码    -->
        <property name="password">123456</property>
        <!--   每次增长的连接数    -->
        <property name="acquireIncrement">3</property>
        <!--   初始化连接数    -->
        <property name="initialPoolSize">10</property>
        <!--   最小的连接数     -->
        <property name="minPoolSize">2</property>
        <!--    最大的连接数    -->
        <property name="maxPoolSize">10</property>
    </default-config>
</c3p0-config>

 

Druid(德鲁伊)数据库连接池

    Druid是阿里提供的数据库连接池,集DBCP、C3P0、Proxool优点与一身的数据库连接池

public void testDruid() throws Exception {
        //1、加入Druid jar包
        //2、加入配置文件druid.properties,将改配置文件拷贝到src目录
        //3、创建一个Properties对象,读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));
        //4、创建一个指定参数的数据库连接池,Druid连接池
        DataSource dataSource =
                DruidDataSourceFactory.createDataSource(properties);
        //5、拿到连接
        Connection connection = null;
        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            connection = dataSource.getConnection();
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("Druid连接数据库5000次耗时:" + (end - start));
    }
#druid.properties文件当中的配置
#加载驱动
driverClassName=com.mysql.jdbc.Driver
#数据库的连接地址
url=jdbc:mysql://127.0.0.1:3306/db01?characterEncoding=utf-8
#连接数据库的用户名
username=root
#连接数据库的密码。
password=123456
#初始化时池中建立的物理连接个数
initialSize=2
#最小的连接数
minIdle=5
#最大的连接数
maxActive=300
#最长的等待时间(毫秒)
maxWait=5000

 

基于Druid的封装的工具类

public class JDBCUtilsByDruid {
    private static DataSource ds; //数据源

    //在静态代码块当中,完成ds初始化操作
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //编写getConnection方法
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //关闭连接,在连接池当中说的关闭连接,是将连接放入到连接池当中
    public static void closeConnection(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            //将编译异常转换为运行异常抛出
            throw new RuntimeException(e);
        }
    }
}

 

标签:数据库,连接,connection,comboPooledDataSource,方法,properties,连接池
From: https://www.cnblogs.com/dbcxy/p/16941080.html

相关文章

  • TypeError: Cannot read property 'length' of undefined 的解决方法
    有可能是数据还没有加载出来,可使用是否为undefined进行判断:for(vari=0,len1=medList.length;i<len1;i++){varpartList=[]//判......
  • 比 Redis 快 25 倍的内存数据库!
    今年年中,一位前谷歌、前亚马逊的工程师推出了他创作的开源内存数据缓存系统Dragonfly,用C/C++编写,基于BSL许可(BusinessSourceLicense)分发。根据过往的基准测试结果来......
  • Linux下用rm误删除文件的三种恢复方法
    对于rm,很多人都有惨痛的教训。我也遇到一次,一下午写的程序就被rm掉了,幸好只是一个文件,第二天很快又重新写了一遍。但是很多人可能就不像我这么幸运了。本文收集了一些在Lin......
  • python连接数据库
    一、python连接mysqlpython连接MySQL使用pymysql库。1、安装:pipinstallpymysql2、代码importpymysql#建立连接db=pymysql.connect(host="127.0.0.1",port=3306......
  • 数据库之 表与表之间的关系
    数据库之表与表之间的关系表1foreignkey表2则表1的多条记录对应表2的一条记录,即多对一利用foreignkey的原理我们可以制作两张表的多对多,一对一关系多对多:......
  • MySQL数据库的定时备份与还原
    一.MySQL备份1.Cron是Linux的内置服务,可以用以下的方法启动、关闭这个服务:servicecrondstart//启动服务servicecrondstop//关闭服务servicecrondrestart/......
  • js 对象属性过滤方法
    有时候需要剔除少数属性,留下大多数。类似于TS的omit例子:letperson={name:"jackchen",age:54,address:'hongkong'}let{name,...xiaohong}=personcons......
  • VM系列振弦采集模块的激励方法
    河北稳控科技VM系列振弦采集模块的激励方法 通过修改寄存器EX_METH.[3:0]来完成激励方法的选择,EX_METH[4]用于设置是否忽略传感器的接入检测而强制发送激励信号。......
  • 稀疏矩阵之 toarray 方法和 todense 方法
    在SciPy稀疏矩阵中,有着2个经常被混为一谈的方法:toarray() 方法以及todense() 方法。事实上,我在才开始接触SciPy稀疏矩阵的时候也曾经把这2个方法之间画上等号。......
  • 超聚变服务器操作系统FusionOS与阿里云PolarDB数据库完成兼容性认证
    近日,超聚变服务器操作系统FusionOS签署阿里巴巴开源CLA(ContributionLicenseAgreement,贡献许可协议),正式与阿里云PolarDB开源数据库社区牵手,并率先展开超聚变服务器......