JavaWeb C3P0資料來源——通過配置檔案建立資料來源物件
阿新 • • 發佈:2018-12-03
在JDBC基本操作中,每次操作資料庫都需要建立和斷開一次Connection物件,
但是如果訪問操作十分頻繁的話,就會十分影響訪問資料庫的問題,想要解決這個問題就需要使用資料庫連線池,
C3P0是現在很流行的開源資料庫連線池,
下面是一個通過配置檔案建立資料來源物件
1、建立配置檔案
在eclipse中建立一個名為web-chapter10的web專案,並在其src中建立配置檔案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/jdbc </property> <property name="user">root</property> <property name="password">itcast</property> <property name="checkoutTimeout">30000</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <named-config name="itcast"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl"> jdbc:mysql://localhost:3306/jdbc </property> <property name="user">root</property> <property name="password">itcast</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">15</property> </named-config> </c3p0-config>
其中default-config是指預設配置,named-config是自定義配置
2、匯入jar包
3、建立測試類
在src下建立cn.itcast.chapter10.example包,並在包中建立Example1類,程式碼如下:
package cn.itcast.chapter10.example; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class Example04 { public static DataSource ds = null; // 初始化C3P0資料來源 static { // 使用c3p0-config.xml配置檔案中的named-config節點中name屬性的值 ComboPooledDataSource cpds = new ComboPooledDataSource("itcast"); ds = cpds; } public static void main(String[] args) throws SQLException { System.out.println(ds.getConnection()); } }
4,測試
執行類中的main方法,得到如下:
至此使用配置檔案連線C3P0資料來源的實驗就完成了