來(lái)源:來(lái)自師范的學(xué)渣 發(fā)布時(shí)間:2018-12-08 11:30:16 閱讀量:1108
在JDBC基本操作中,每次操作數(shù)據(jù)庫(kù)都需要?jiǎng)?chuàng)建和斷開(kāi)一次Connection對(duì)象,
但是如果訪問(wèn)操作十分頻繁的話,就會(huì)十分影響訪問(wèn)數(shù)據(jù)庫(kù)的問(wèn)題,想要解決這個(gè)問(wèn)題就需要使用數(shù)據(jù)庫(kù)連接池,
C3P0是現(xiàn)在很流行的開(kāi)源數(shù)據(jù)庫(kù)連接池,
下面是一個(gè)通過(guò)配置文件創(chuàng)建數(shù)據(jù)源對(duì)象
1、創(chuàng)建配置文件
在eclipse中創(chuàng)建一個(gè)名為web-chapter10的web項(xiàng)目,并在其src中創(chuàng)建配置文件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是指默認(rèn)配置,named-config是自定義配置
2、導(dǎo)入jar包
3、創(chuàng)建測(cè)試類
在src下創(chuàng)建cn.itcast.chapter10.example包,并在包中創(chuàng)建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數(shù)據(jù)源
static {
// 使用c3p0-config.xml配置文件中的named-config節(jié)點(diǎn)中name屬性的值
ComboPooledDataSource cpds = new ComboPooledDataSource("itcast");
ds = cpds;
}
public static void main(String[] args) throws SQLException {
System.out.println(ds.getConnection());
}
}
4,測(cè)試
運(yùn)行類中的main方法,得到如下:
至此使用配置文件連接C3P0數(shù)據(jù)源的實(shí)驗(yàn)就完成了
---------------------
在線
客服
服務(wù)時(shí)間:周一至周日 08:30-18:00
選擇下列產(chǎn)品馬上在線溝通:
客服
熱線
7*24小時(shí)客服服務(wù)熱線
關(guān)注
微信
關(guān)注官方微信