首先我們需要知道為什麼要使用連接池:因為jdbc沒有保持連接的能力,一旦超過一定時間沒有使用(大約幾百毫秒),連接就會被自動釋放掉,每次新建連接都需要140毫秒左右的時間而C3P0連接池會池化連接,隨時取用,平均每次取用只需要10-20毫秒,所以如果是很多客戶端並發隨機訪問數據庫的話,使用連接池的效率會高。
接下來我們看使用c3p0需要做那些准備:首先需要導入相對應的jar包:c3p0-0.9.1.2-jdk1.3.jar,然後就是鏈接數據庫的配置文件:c3p0-config.xml,配置如下
1 <?xml version="1.0" encoding="UTF-8"?> 2 <c3p0-config> 3 <!-- This is default config! --> 4 <default-config> 5 <property name="initialPoolSize">10</property> 6 <property name="maxIdleTime">30</property> 7 <property name="maxPoolSize">100</property> 8 <property name="minPoolSize">10</property> 9 <property name="maxStatements">200</property> 10 </default-config> 11 12 <!-- This is my config for mysql--> 13 <named-config name="mysql"> 14 <!-- 加載驅動 --> 15 <property name="driverClass">com.mysql.jdbc.Driver</property> 16 <!-- 其中studio為數據庫名稱 --> 17 <property name="jdbcUrl">jdbc:mysql://localhost:3306/studio?useUnicode=true&characterEncoding=UTF8</property> 18 <!-- 連接用戶名 --> 19 <property name="user">root</property> 20 <!-- 連接密碼 --> 21 <property name="password"></property> 22 <property name="initialPoolSize">10</property> 23 <property name="maxIdleTime">30</property> 24 <property name="maxPoolSize">100</property> 25 <property name="minPoolSize">10</property> 26 <property name="maxStatements">200</property> 27 </named-config> 28 </c3p0-config>
接下來是c3p0鏈接數據庫的工具類,調用此類之後我們就無需再手動關閉連接,代碼如下
1 import java.sql.Connection;
2 import java.sql.PreparedStatement;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5
6 import com.mchange.v2.c3p0.ComboPooledDataSource;
7 public class C3P0Util {
8 static ComboPooledDataSource cpds=null;
9 static{
10 cpds = new ComboPooledDataSource("mysql");//這是mysql數據庫
11 }
12 /**
13 * 獲得數據庫連接
14 */
15 public static Connection getConnection(){
16 try {
17 return cpds.getConnection();
18 } catch (SQLException e) {
19 e.printStackTrace();
20 return null;
21 }
22 }
23
24 /**
25 * 數據庫關閉操作
26 */
27 public static void close(Connection conn,PreparedStatement pst,ResultSet rs){
28 if(rs!=null){
29 try {
30 rs.close();
31 } catch (SQLException e) {
32 e.printStackTrace();
33 }
34 }
35 if(pst!=null){
36 try {
37 pst.close();
38 } catch (SQLException e) {
39 e.printStackTrace();
40 }
41 }
42
43 if(conn!=null){
44 try {
45 conn.close();
46 } catch (SQLException e) {
47 e.printStackTrace();
48 }
49 }
50 }
51 }
最後我們只需要在自己寫的Dao層操作中獲取到C3p0的連接就好了,這裡我就只寫一個查詢的方法
public List<String> getSelect() {
// sql語句
String sql = "select * from user";
// 獲取到連接
Connection conn = C3P0Util.getConnection();
PreparedStatement pst = null;
// 定義一個list用於接受數據庫查詢到的內容
List<String> list = new ArrayList<String>();
try {
pst = (PreparedStatement) conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
// 將查詢出的內容添加到list中,其中userName為數據庫中的字段名稱
list.add(rs.getString("userName"));
}
} catch (Exception e) {
}
return list;
}
主要是第5行中獲取鏈接的方式改變了,當然我們既然鏈接數據庫就需要導入相對應的jar包