数据库连接池

来源:互联网 发布:android 数据共享方式 编辑:程序博客网 时间:2024/05/01 21:41
数据库连接池

数据库连接池必须实现javax.sql.DataSource接口
配置四大参数
连接池的Connection对象的close方法:是将该连接归还给连接池
*连接池使用了装饰者模式对Connection对象进行了装饰

dbcp连接池:

package com.jdbc;import java.sql.Connection;import java.sql.SQLException;import org.apache.commons.dbcp.BasicDataSource;import org.junit.Test;public class Demo1 {@Testpublic void fun() throws SQLException{/* * 创建连接池对象 * 配置四大参数 * 配置池参数 * 得到连接对象 * */BasicDataSource dataSource = new BasicDataSource();dataSource.setDriverClassName("com.mysql.jdbc.Driver");dataSource.setUrl("jdbc:mysql://localhost:3306/myssh");dataSource.setUsername("root");dataSource.setPassword("123");dataSource.setMaxActive(20);dataSource.setMinIdle(3);dataSource.setMaxWait(1000);Connection con = dataSource.getConnection();System.out.println(con.getClass().getName());}}

c3p0连接池:

public void fun() throws PropertyVetoException, SQLException{//创建连接池对象ComboPooledDataSource dataSource = new ComboPooledDataSource();//对池进行四大参数的配置dataSource.setDriverClass("com.mysql.jdbc.Driver");dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/myssh");dataSource.setUser("root");dataSource.setPassword("123");//池参数配置dataSource.setAcquireIncrement(5);dataSource.setInitialPoolSize(20);dataSource.setMinPoolSize(2);dataSource.setMaxPoolSize(50);//得到连接Connection con = dataSource.getConnection();System.out.println(con);con.close();}
使用c3p0配置文件

文件名称:c3p0-config.xml

文件位置:在src下

<?xml version="1.0" encoding="UTF-8"?><c3p0-config><default-config><property name="jdbcUrl">jdbc:mysql://localhost:3306/myssh</property><property name="driverClass">com.mysql.jdbc.Driver</property><property name="user">root</property><property name="password">123</property><property name="acquireInorement">3</property><property name="initialPoolSize">10</property><property name="minPoolSize">2</property><property name="maxPoolSize">10</property></default-config></c3p0-config>

public void fun1() throws SQLException{ComboPooledDataSource dataSource = new ComboPooledDataSource();Connection con = dataSource.getConnection();System.out.println(con);con.close();}


0 0
原创粉丝点击