---
title: "C3P0数据源使用"
author: "macheng365"
date: "2011-12-13T15:16:32Z"
tags: []
categories: ["数据库"]
slug: "c3p0"
draft: false
lastmod: "2011-12-13T15:16:32Z"
id: 1308680
url: "https://macheng365.iteye.com/blog/1308680"
---

```
package   C3P0; 
import   java.sql.Connection; 
import   java.sql.SQLException; 
import   java.beans.PropertyVetoException; 
import   com.mchange.v2.c3p0.ComboPooledDataSource; 
public   class   DBPool{       
    private   static   DBPool   dbPool;       
    private   ComboPooledDataSource   dataSource;     

    static   {       
            dbPool=new   DBPool();       
    }       
    
    public   DBPool(){       
            try   {       
                    dataSource=new   ComboPooledDataSource();       
                    dataSource.setUser( "id ");       
                    dataSource.setPassword( "pw ");       
                    dataSource.setJdbcUrl( "jdbc:mysql://127.0.0.1:3306/test? 

autoReconnect=true&useUnicode=true&characterEncoding=GB2312 "); 
                    dataSource.setDriverClass( "com.mysql.jdbc.Driver "); 
                    dataSource.setInitialPoolSize(2); 
                    dataSource.setMinPoolSize(1); 
                    dataSource.setMaxPoolSize(10); 
                    dataSource.setMaxStatements(50); 
                    dataSource.setMaxIdleTime(60);       
            }   catch   (PropertyVetoException   e)   {       
                throw   new   RuntimeException(e);       
            }       
    }       

    public   final   static   DBPool   getInstance(){       
            return   dbPool;       
    }       

    public   final   Connection   getConnection()   {       
            try   {       
                    return   dataSource.getConnection();       
            }   catch   (SQLException   e)   {       
                    throw   new   RuntimeException( "无法从数据源获取连接 ",e);       
            }       
    }     
    
    public   static   void   main(String[]   args)   throws   SQLException   { 
Connection   con   =   null; 
try   { 
con   =   DBPool.getInstance().getConnection(); 
}   catch   (Exception   e){ 
}   finally   { 
if   (con   !=   null) 
con.close(); 
} 
} 
}
```

 

引用 8 楼 xyflash 的回复:  
每用一次都要  
Connection conn = DBPool.getInstance.getConnection();  
一次。。感觉没起到连接池的作用啊

楼主，使用连接池的时候并不是在代码中不用获取/释放数据库连接，而是在代码中向连接池申请/释放连接，对于代码而言，可以把连接池看成数据库。

换句话说，连接池就是数据库的代理，之所以要使用这个代理是因为直接向数据库申请/释放连接是要降低性能的：如果每一次数据访问请求都必须经历建立数据库连接、打开数据库、存取数据和关闭数据库连接等步骤，而连接并打开数据库是一件既消耗资源又费时的工作，那么频繁发生这种数据库操作时，系统的性能必然会急剧下降。

连接池的作用是自己维护数据库连接，数据库连接池的主要操作如下：  
　　（1）建立数据库连接池对象（服务器启动）。  
　　（2）按照事先指定的参数创建初始数量的数据库连接（即：空闲连接数）。  
　　（3）对于一个数据库访问请求，直接从连接池中得到一个连接。如果数据库连接池对象中没有空闲的连接，且连接数没有达到最大（即：最大活跃连接数），创建一个新的数据库连接。  
　　（4）存取数据库。  
　　（5）关闭数据库，释放所有数据库连接（此时的关闭数据库连接，并非真正关闭，而是将其放入空闲队列中。如实际空闲连接数大于初始空闲连接数则释放连接）。  
　　（6）释放数据库连接池对象（服务器停止、维护期间，释放数据库连接池对象，并释放所有连接）。

 

 

 

 

 

 

 

**我刚刚写了一个很简单的C3P0使用示例，分别测试了使用连接池和不使用连接池时的性能差异。**

```
package com.lnbdqn;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public final class ConnectionManager {

    private static ConnectionManager instance;
    private static ComboPooledDataSource dataSource;

    private ConnectionManager() throws SQLException, PropertyVetoException {
        dataSource = new ComboPooledDataSource();

        dataSource.setUser("loux");
        dataSource.setPassword("loux");
        dataSource.setJdbcUrl("jdbc:oracle:thin:@192.168.100.70:1521:orcl");
        dataSource.setDriverClass("oracle.jdbc.driver.OracleDriver");
        dataSource.setInitialPoolSize(5);
        dataSource.setMinPoolSize(1);
        dataSource.setMaxPoolSize(10);
        dataSource.setMaxStatements(50);
        dataSource.setMaxIdleTime(60);
    }

    public static final ConnectionManager getInstance() {
        if (instance == null) {
            try {
                instance = new ConnectionManager();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return instance;
    }

    public synchronized final Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}



```

 

```
package com.lnbdqn;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import oracle.jdbc.pool.OracleDataSource;

public class ConnectionDemo {

    public static void main(String[] args) throws SQLException {
        System.out.println("使用连接池................................");
        for (int i = 0; i < 20; i++) {
            long beginTime = System.currentTimeMillis();
            Connection conn = ConnectionManager.getInstance().getConnection();
            try {
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM t_fmscpy200");
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            long endTime = System.currentTimeMillis();
            System.out.println("第" + (i + 1) + "次执行花费时间为:" + (endTime - beginTime));
        }

        System.out.println("不使用连接池................................");
        for (int i = 0; i < 20; i++) {
            long beginTime = System.currentTimeMillis();
            OracleDataSource ods = new OracleDataSource();
            ods.setUser("loux");
            ods.setPassword("loux");
            ods.setURL("jdbc:oracle:thin:@192.168.100.70:1521:orcl");
            Connection conn = ods.getConnection();
            try {
                PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM table_name");
                ResultSet rs = pstmt.executeQuery();
                while (rs.next()) {
                                    // do nothing...
                }
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            long endTime = System.currentTimeMillis();
            System.out.println("第" + (i + 1) + "次执行花费时间为:"
                                + (endTime - beginTime));
        }

    }
}



```

 

控制台输出的结果为：

**使用连接池................................**  
第1次执行花费时间为:1469  
第2次执行花费时间为:0  
第3次执行花费时间为:16  
第4次执行花费时间为:0  
第5次执行花费时间为:0  
第6次执行花费时间为:15  
第7次执行花费时间为:0  
第8次执行花费时间为:0  
第9次执行花费时间为:0  
第10次执行花费时间为:0  
第11次执行花费时间为:16  
第12次执行花费时间为:0  
第13次执行花费时间为:0  
第14次执行花费时间为:0  
第15次执行花费时间为:0  
第16次执行花费时间为:16  
第17次执行花费时间为:0  
第18次执行花费时间为:0  
第19次执行花费时间为:15  
第20次执行花费时间为:0  
**不使用连接池................................**  
第1次执行花费时间为:47  
第2次执行花费时间为:31  
第3次执行花费时间为:32  
第4次执行花费时间为:46  
第5次执行花费时间为:32  
第6次执行花费时间为:31  
第7次执行花费时间为:47  
第8次执行花费时间为:31  
第9次执行花费时间为:47  
第10次执行花费时间为:31  
第11次执行花费时间为:47  
第12次执行花费时间为:31  
第13次执行花费时间为:32  
第14次执行花费时间为:46  
第15次执行花费时间为:47  
第16次执行花费时间为:32  
第17次执行花费时间为:46  
第18次执行花费时间为:47  
第19次执行花费时间为:32  
第20次执行花费时间为:31

**可以看出，在使用连接池时，第一次执行花费的时间稍长，因为第一次初始化操作需要创建多个连接并放入池中，以后使用时将会大大缩短执行时间。**  
**在不使用连接池时，每次花费的时间都比较长。**