1. 首先要导入C3P0的jar包
下载地址
https://download.csdn.net/download/lingxing9454/10655322
不要忘记导入MySql的jar包
2. 导入配置文件
配置文件名称必须为:c3p0-config.xml
配置文件格式如下:
要放在Src中 否则会报错
<?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/数据库名称</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<named-config name="oracle">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/数据库名称</property>
<property name="user">root</property>
<property name="password">root</property>
</named-config>
</c3p0-config>
3. 编写C3P0工具类
public class C3P0Utils {
public static ComboPooledDataSource pd = new ComboPooledDataSource();
public static DataSource getDataSource() {
return pd;
}
public static Connection getConnection() {
try {
return pd.getConnection();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public static void close(Connection conn,PreparedStatement pst,ResultSet rs){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4.测试C3P0!
public class UnitTest {
@Test
public void TestUnit() {
Connection connection=C3P0Utils.getConnection();
System.out.println(connection);
}
}
输出 [email protected] 则证明可以使用C3P0