C3P0
所需jar包:c3p0-0.9.5.2.jar、mysql-connector-java-8.0.17-bin.jar
系统会自动读取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/db_mysqltest</property>
<property name="user">root</property>
<property name="password">root</property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement">3</property>
<!-- 初始化连接池中的连接数,取值应在minPoolSize与maxPoolSize之间,默认为3-->
<property name="initialPoolSize">10</property>
<!-- 连接池中保留的最小连接数,默认为:3-->
<property name="minPoolSize">2</property>
<!--连接池中保留的最大连接数。默认值: 15 -->
<property name="maxPoolSize">10</property>
</default-config>
</c3p0-config>
编写数据源工具类:
public class C3P0Utils {
//得到一个数据源(连接池)
private static DataSource ds = new ComboPooledDataSource();
public static DataSource getDataSource(){
return ds;
}
//获取数据库连接对象
public static Connection getConnection() throws SQLException{
Connection con;
try {
con = ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException("服务器忙");
}
return con;
}
//关闭所有资源连接
public static void closeAll(ResultSet set,Statement statement,Connection connection){
if (set != null) {
try {
set.close();
} catch (SQLException e2) {
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e2) {
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}