
概念:其实就是一个容器(集合),用于存放数据库连接的容器。当系统初始化后,容器会申请一些连接对象存放在容器中,当用户访问数据时,会从容器中获取连接对象,结束时归还连接对象给容器。
优势:
节约资源
利用的效率高
数据连接池:
C3P0
Druid (阿里巴巴)
实现步骤:
导入jar包(c3p0-0.9.1.2.jar 和 mchange-commons-java-0.2.12 jar)
定义配置文件:c3p0-config.xml 或 c3p0.properties(放入src目录)
创建数据库连接池对象 ComboPooledDataSource
配置文件:c3p0-config.xml
<?xml version="1.0" encoding="utf-8"?><c3p0-config><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql://localhost:3306/student</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>
简单测试:(省略异常处理)
main {// 1.导入jar包,配置文件// 2.创建数据库连接池对象DataSource dateSource = new ComboPooledDataSource();// 3.获取数据连接对象Connection connection = dataSource.getConnection();// 4.测试System.out.println(connection);// 5.归还数据库连接对象connection.close();}

配置文件的参数的验证:
initialPoolSize:5
maxPoolSize:10
checkoutTimeout:3000
otherc3p0
main {// 获取数据库对象DataSource ds = new ComboPooledDataSource();// 获取数据连接对象for (int i = 1; i <= 11; i++ ) {Connection conn = ds.getConnection();System.out.println(i + ":" + conn);if(i == 5) {conn.close();}}}

文章转载自南京的萝卜,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




