连接池的意义
-
首先,我们聊聊不使用连接池,会有什么问题
如果不使用连接池,每次访问数据库都要创建Connection对象,使用完后,都要销毁Connection对象;
而Connection对象在访问数据库时,是很重要的资源,每次创建或者销毁都要消耗大量的时间,当数据库访问量比较大时,会导致网页非常卡,程序运行速度迟缓。 -
这时候,我们引入连接池的概念
就是在程序初始化时,我们就预先创建一些Connection连接对象,放入一个Connection对象的容器中;
当需要访问数据库时,我们不再创建Connection对象,而是从这个容器中取出Connection对象使用;
用完也不用销毁,再放入容器中,等待其他客户访问时使用。 -
这样,极大程度上减少了Connection对象创建和销毁的时间,提升程序的运行性能。
如何自定义连接池
- 首先我们定义一个java类,在此类中初始化一些连接池对象;
- 当程序需要用到connection对象时,调用此类方法获取connection对象;
- 点程序使用完connection对象时,调用此类方法归还connection对象。
代码如下所示:
public static class MydataSource{
//1.
private static List<Connection> list = new ArrayList<Connection>();
public MydataSource(){
for (int i = 0; i < 3; i++) {
list.add(JDBCUtils.getConnection());
}
}
//2.
public static Connection getConnection(){
if(list.size() == 0){
return JDBCUtils.getConnection();
}
return list.remove(0);
}
//3.
public static void closeConnection(Connection connection){
list.add(connection);
}
}
Druid连接池使用
- 导包
druid-1.0.9.jar
- 直接使用
DruidDataSource dataSource = new DruidDataSource(); // 手动设置数据库连接的参数: dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql:///web_test4"); dataSource.setUsername("root"); dataSource.setPassword("abc"); // 获得连接: conn = dataSource.getConnection();
- 以读取外部文件的方式使用
- 外部文件druid.properties
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbc username=root password=root //初始化连接数 initialSize=10 //最大连接数 maxActive=50 maxIdle=20 minIdle=5 maxWait=60000
- java类中使用
Properties properties = new Properties(); properties.load(new FileInputStream("src/druid.properties")); DataSource dataSource = DruidDataSourceFactory.createDataSource(properties); // 获得连接: conn = dataSource.getConnection();
- 外部文件druid.properties
C3P0连接池
- 导包
c3p0-0.9.1.2.jar
- 直接使用
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 设置连接参数:
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql:///web_test4");
dataSource.setUser("root");
dataSource.setPassword("abc");
// 从连接池中获得连接:
conn = dataSource.getConnection();
- 使用导入外部文件的方式使用
- 在c3p0.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://web_test4</property>
<property name="user">root</property>
<property name="password">abc</property>
<property name="initialPoolSize">5</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
* java代码中引用
// 创建连接池://创建连接池默认去类路径下查找c3p0-config.xml
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 从连接池中获得连接:
conn = dataSource.getConnection();