您好,登錄后才能下訂單哦!
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 國真
* 1. 需要兩個jar包:c3p0-0.9.2-pre1.jar 和 mchange-commons-0.2.jar
* 2. fun1()使用代碼來創建連接池對象
* fun2()使用默認配置,<default-config>
* fun3()使用命名配置,<name-config name="mysqlConfig">
*/
public class Demo {
@Test
public void fun1() throws PropertyVetoException, SQLException{
//創建連接池對象
ComboPooledDataSource ds = new ComboPooledDataSource();
//連接參數配置(四大參數)
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對象所代表的具體對象的名稱
connection.close();
}
@Test
public void fun2() throws PropertyVetoException, SQLException{
//創建連接池對象
ComboPooledDataSource ds = new ComboPooledDataSource();
Connection connection = ds.getConnection();
System.out.println(connection.getClass().getName());
connection.close();
//關閉池連接
ds.close();
}
@Test
public void fun3() throws PropertyVetoException, SQLException{
//創建連接池對象
ComboPooledDataSource ds = new ComboPooledDataSource("mysqlConfig"); //若給出了參數,則該參數就是<name-config>的名稱
Connection connection = ds.getConnection();
System.out.println(connection.getClass().getName());
connection.close();
//關閉池連接
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>
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。