当前位置: 首页 > news >正文

C3P0和Druid数据库连接池的使用

本次博客带领大家学习C3P0和Druid数据库连接池的使用。

传统方式连接数据库

  • 连接5000次数据库的耗时。
public void testCon(){

    //看看连接 - 关闭 connection 会耗用多久
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        //使用传统的jdbc方式,得到连接
        Connection connection = JDBCUtils.getConnection();

        //关闭
        JDBCUtils.close(null,null,connection);
    }
    long end = System.currentTimeMillis();
    System.out.println("传统方式连接 5000次数据库 耗时="+(end-start));
}

C3P0数据库连接池的使用

  • 方式一:传入相关参数,在程序中指定user,url,password等。
public void testC3P0_01() throws Exception {
    //1.创建一个数据源对象
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    //2.通过配置文件mysql.properties 获取相关连接的信息。
    Properties properties = new Properties();
    properties.load(new FileInputStream("src\\mysql.properites"));
    String user = properties.getProperty("user");
    String password = properties.getProperty("password");
    String driver = properties.getProperty("driver");
    String url = properties.getProperty("url");

    //给数据源  comboPooledDataSource 设置相关的参数
    //注意:连接管理是由 comboPooledDataSource 来管理
    comboPooledDataSource.setDriverClass(driver);
    comboPooledDataSource.setJdbcUrl(url);
    comboPooledDataSource.setUser(user);
    comboPooledDataSource.setPassword(password);
    //设置初始化连接数
    comboPooledDataSource.setInitialPoolSize(10);
    comboPooledDataSource.setMaxPoolSize(50);
    //测试连接池的效率,测试对mysql 5000次操作
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        Connection connection = comboPooledDataSource.getConnection();//这个方法就是从 DataSource 来实现
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("c3p0 5000次连接mysql 耗时="+(end-start));
}
  • 方式二:使用配置文件模板来完成。
<?xml version="1.0" encoding="utf-8"?>
<--!>xml配置文件</--!>
<c3p0-config>
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/ld_db01</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
  </named-config>
</c3p0-config>
//1.将c3p0 提供c3p0-config.xml 拷贝到 src目录下
//2. 该文件指定了连接数据库和连接池的相关参数
@Test
public void testC3P0_02() throws Exception {
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<5000;i++){
        Connection connection = comboPooledDataSource.getConnection();
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("c3p0 第二次方式 5000次连接mysql 耗时="+(end-start));

}

Druid数据库连接池的使用

  1. 加入 Druid jar包。

  2. 加入配置文件 druid.properties,将该文件拷贝项目的src目录。

  3. 创建Properties对象,读取配置文件。

  4. 创建一个指定参数的数据库连接池。

driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/ld_db01?rewriteBatchedStatements=true
username = root
password = root
initialSize=10
minIdle=5
maxActive=20
maxWait=5000
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);
    System.out.println("开始执行");
    long start = System.currentTimeMillis();
    for (int i=0;i<500000;i++){
        Connection connection = dataSource.getConnection();
        connection.close();
    }
    long end = System.currentTimeMillis();
    System.out.println("druid连接池 500000次连接mysql 耗时="+(end-start));
}

Druid工具类

  • 将JDBCUtils工具类改成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 (Exception e) {
            e.printStackTrace();
        }
    }

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

    //关闭连接,在数据库连接池技术中,close不是真的断掉连接,而是把使用的Connection对象放回连接池
    public static void close(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);
        }
    }
}
public class JDBCUtilsByDruid_USE {
    @Test
    public void testSelect(){
        System.out.println("使用Druid数据库连接池查询:");
        //1. 得到连接
        Connection connection = null;

        // 2.组织一个sql
        String sql = "select * from actor";
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        //3.创建PrepareStatement对象
        try {
            connection = JDBCUtilsByDruid.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while(resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                String sex = resultSet.getString("sex");
                Date borndate = resultSet.getDate("borndate");
                String phone = resultSet.getString("phone");
                System.out.println(id+"\t"+name+"\t"+sex+"\t"+borndate+"\t"+phone);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //关闭资源
            JDBCUtilsByDruid.close(null,preparedStatement,connection);
        }
    }
}

相关文章:

  • 2022中国消费者智能网联汽车数据安全和个人隐私意识与顾虑调查报告
  • Java 大文件分片上传
  • Redis未授权访问漏洞
  • Java 修饰符 private、default、protected、public 的应用实例 (方法)
  • Java 多线程:锁(一)
  • VMware 搭建linux操作系统,入门必看
  • 2022牛客多校(三)
  • 阿里云服务器和腾讯云服务器哪个更好?多维度对比得出了结论
  • sqli-labs(less-1)
  • 【Ubuntu】gcc与Makefile操作
  • Python零基础入门篇 · 21】:构造函数、类属性和实例属性的访问
  • Invalid bound statement (not found)出现的原因和解决方法
  • hive笔记八:自定义函数-自定义UDF函数/自定义UDTF函数
  • Docker从初学到进阶一(初识Docker,CenOS8安装Docker)
  • FreeRTOS的学习(三)—— 信号量之二值信号量
  • [译]Python中的类属性与实例属性的区别
  • 10个最佳ES6特性 ES7与ES8的特性
  • ABAP的include关键字,Java的import, C的include和C4C ABSL 的import比较
  • Apache Pulsar 2.1 重磅发布
  • Apache的80端口被占用以及访问时报错403
  • Computed property XXX was assigned to but it has no setter
  • k8s如何管理Pod
  • Linux下的乱码问题
  • maya建模与骨骼动画快速实现人工鱼
  • MYSQL 的 IF 函数
  • Netty+SpringBoot+FastDFS+Html5实现聊天App(六)
  • overflow: hidden IE7无效
  • Protobuf3语言指南
  • Redis的resp协议
  • 给第三方使用接口的 URL 签名实现
  • 简析gRPC client 连接管理
  • 码农张的Bug人生 - 见面之礼
  • 如何实现 font-size 的响应式
  • 问:在指定的JSON数据中(最外层是数组)根据指定条件拿到匹配到的结果
  • 问题之ssh中Host key verification failed的解决
  • NLPIR智能语义技术让大数据挖掘更简单
  • #Linux(make工具和makefile文件以及makefile语法)
  • (附源码)基于ssm的模具配件账单管理系统 毕业设计 081848
  • (黑马C++)L06 重载与继承
  • (一)kafka实战——kafka源码编译启动
  • (原創) 如何安裝Linux版本的Quartus II? (SOC) (Quartus II) (Linux) (RedHat) (VirtualBox)
  • (转)JAVA中的堆栈
  • (转载)在C#用WM_COPYDATA消息来实现两个进程之间传递数据
  • (最优化理论与方法)第二章最优化所需基础知识-第三节:重要凸集举例
  • ******IT公司面试题汇总+优秀技术博客汇总
  • .htaccess配置重写url引擎
  • .net 4.0发布后不能正常显示图片问题
  • .net core Swagger 过滤部分Api
  • .net 验证控件和javaScript的冲突问题
  • .NET 中什么样的类是可使用 await 异步等待的?
  • .Net程序帮助文档制作
  • .net企业级架构实战之7——Spring.net整合Asp.net mvc
  • .NET值类型变量“活”在哪?
  • .vue文件怎么使用_vue调试工具vue-devtools的安装
  • /使用匿名内部类来复写Handler当中的handlerMessage()方法