学习了如何使用C3P0后,经常容易忘,所以写下来以便对以后有所帮助。
1.添加jar包
使用C3P0数据源需要添加c3p0-0.9.1.2.jar,mysql-connector-java-5.0.8-bin.jar两个jar包
2.编写配置文件
使用C3P0需要编写 c3p0-config.xml 文件 ,放在java web项目中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/123</property>
<property name="user">root</property>
<property name="password">abc</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>
3.
编写工具类
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* @author: Jeson
* @date:2017-12-24 下午3:08:29
* @version :
*
*/
public class C3P0Util {
private static ComboPooledDataSource datasource = new ComboPooledDataSource();
public static Connection getConnection() {
try {
return datasource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException("创建数据库连接失败……");
}
}
public static void release(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
rs = null;
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
stmt = null;
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
conn = null;
}
}