您好,登錄后才能下訂單哦!
package cn.itcast.test;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 演示c3p0連接池
* @author 國(guó)真
* 1. 需要兩個(gè)jar包:c3p0-0.9.2-pre1.jar 和 mchange-commons-0.2.jar
* 2. fun1()使用代碼來(lái)創(chuàng)建連接池對(duì)象
* fun2()使用默認(rèn)配置,<default-config>
* fun3()使用命名配置,<name-config name="mysqlConfig">
*/
public class Demo {
@Test
public void fun1() throws PropertyVetoException, SQLException{
//創(chuàng)建連接池對(duì)象
ComboPooledDataSource ds = new ComboPooledDataSource();
//連接參數(shù)配置(四大參數(shù))
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
ds.setUser("root");
ds.setPassword("admin");
//池配置省略
//獲取連接
Connection connection = ds.getConnection();
System.out.println(connection.getClass().getName()); //返回connection對(duì)象所代表的具體對(duì)象的名稱(chēng)
connection.close();
}
@Test
public void fun2() throws PropertyVetoException, SQLException{
//創(chuàng)建連接池對(duì)象
ComboPooledDataSource ds = new ComboPooledDataSource();
Connection connection = ds.getConnection();
System.out.println(connection.getClass().getName());
connection.close();
//關(guān)閉池連接
ds.close();
}
@Test
public void fun3() throws PropertyVetoException, SQLException{
//創(chuàng)建連接池對(duì)象
ComboPooledDataSource ds = new ComboPooledDataSource("mysqlConfig"); //若給出了參數(shù),則該參數(shù)就是<name-config>的名稱(chēng)
Connection connection = ds.getConnection();
System.out.println(connection.getClass().getName());
connection.close();
//關(guān)閉池連接
ds.close();
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">admin</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</default-config>
<name-config name="mysqlConfig">
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">admin</property>
<property name="acquireIncrement">3</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">2</property>
<property name="maxPoolSize">10</property>
</name-config>
</c3p0-config>
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。