C3P0连接池连接数据库,我在用的时候遇到了一个问题,那就是每次连接数据库后没有关闭,然后就导致达到最大连接数以后,数据库就不连接了,所以一定要关闭,当然在用一些框架的时候,框架里有封装的管理数据库的,那就不用关闭。
在src目录下创建c3p0-config.xml配置文件
c3p0-config.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<c3p0-config>
<default-config>
<property name="随便填个名字"></property>
<property name="driverClass">驱动名</property>
<property name="jdbcUrl">url</property>
<property name="user">用户名</property>
<property name="password">用户密码</property>
<property name="maxIdleTime">连接的最大空闲时间</property>
<property name="maxPoolSize">连接池中拥有的最大连接数</property>
<property name="maxStatements">连接池为数据源缓存的PreparedStatement的总数</property>
</default-config>
</c3p0-config>
比如连接PostgreSQL
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/2002/xmlspec/dtd/2.10/xmlspec.dtd">
<c3p0-config>
<default-config>
<property name="postgres"></property>
<property name="driverClass">org.postgresql.Driver</property>
<property name="jdbcUrl">jdbc:postgresql://localhost:5432/postgres</property>
<property name="user">postgres</property>
<property name="password">postgres</property>
<property name="maxIdleTime">10</property>
<property name="maxPoolSize">50</property>
<property name="idleConnectionTestPeriod">10</property>
<property name="maxStatements">200</property>
</default-config>
</c3p0-config>
连接数据库的java代码
import java.sql.*;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
static ComboPooledDataSource dataSource = new ComboPooledDataSource("postgres");
public static Connection getConnection() {
Connection con = null;
try {
con = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return con;
}
在其他类中连接数据库只需要在连接数据库的地方加上一句代码
con = JdbcUtils.getConnection();
c3p0需要的jar包有: