作者:一个关于摄影的家伙 | 来源:互联网 | 2023-10-12 11:19
C3P0 连接池获取的connection执行close() 方法是释放资源销毁连接还是释放资源归还连接至连接池?
如果你只是想要一个答案的话,可以很明确的说: 连接池的连接对象在执行clos()方法之后, 是将资源释放出来但连接不被销毁,而是重新回到C3P0 连接池中以重复使用。
代码演示如下:
## 一:C3P0 的硬编码方式演示
package com.Demo_c3p0使用_硬编码;import com.mchange.v2.c3p0.ComboPooledDataSource;import java.sql.Connection;import java.sql.PreparedStatement;
import java.sql.ResultSet;public class Hard_Coding {public static void main(String[] args) throws Exception {
ComboPooledDataSource cps = new ComboPooledDataSource();
cps.setDriverClass("com.mysql.jdbc.Driver");cps.setJdbcUrl("jdbc:mysql://localhost:3306/mydb1");cps.setUser("root");cps.setPassword("1234");
cps.setInitialPoolSize(3);
Connection connection = cps.getConnection();
String sql = "select * from exam where math in (?,?,?);";PreparedStatement ps = connection.prepareStatement(sql);ps.setInt(1, 89);ps.setInt(2, 85);ps.setInt(3, 91);
ResultSet resultSet = ps.executeQuery();while (resultSet.next()) {int id = resultSet.getInt("id");String name = resultSet.getString("name");int chinese = resultSet.getInt("chinese");int math = resultSet.getInt("math");int english = resultSet.getInt("english");System.out.println(id + " " + name + " " + chinese + " " + math + " " + english);}System.out.println("被占用的连接数: " + cps.getNumBusyConnections());System.out.println("连接池中的总连接数:" + cps.getNumConnections());resultSet.close();ps.close();connection.close();Thread.sleep(60000);System.out.println("被占用的连接数: " + cps.getNumBusyConnections());System.out.println("连接池中的总连接数:" + cps.getNumConnections());}
}
执行结果如下:
值得一提的是,
如果将释放资源的代码注释掉, 可以发现
System.out.println("被占用的连接数: " + cps.getNumBusyConnections());System.out.println("连接池中的总连接数:" + cps.getNumConnections());Thread.sleep(6000);System.out.println("被占用的连接数: " + cps.getNumBusyConnections());System.out.println("连接池中的总连接数:" + cps.getNumConnections());
那么执行结果:将资源释放代码注释掉后,即使DQL 执行完毕,连接也没有被释放
## 二:C3P0 的配置文件c3p0-config.xml 的使用方式
C3P0 的硬编码模式和通过配置文件的方式没有什么区别,配置文件的方式只是将连接的属性包装在了一个文件中,在项目其他文件需要的时候能够通过其他方式(如Dom4j 类)将配置引入。c3p0-config.xml 默认需要放在当前模块代码的src 目录下, 以供c3p0 在创建连接池的时候进行数据库相关参数数据的获取。
c3p0-config.xml 文件配置:
<!--c3p0-config.xml 文件格式内容如下&#xff0c;如果需要其他的参数&#xff0c;例如重连次数、日志输出等 -->
<c3p0-config><default-config><property name&#61;"driverClass">com.mysql.jdbc.Driver</property><property name&#61;"jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property><property name&#61;"user">root</property><property name&#61;"password">1234</property><property name&#61;"initialPoolSize">6</property></default-config>
</c3p0-config>
执行结果&#xff1a;同硬编码方式。资源释放后&#xff0c;连接归还连接池。
注掉释放资源的代码后&#xff0c;可以发现被占用的连接不会得到释放。