连接池
1.连接池原理
2.c3p0连接池
3.c3p0连接池的使用
package c3p0;
import com.mchange.v2.c3p0.*;
import java.beans.PropertyVetoException;
import java.sql.Connection;
public class Demo01 {
public static void main(String[] args) throws Exception {
//创建了cep0连接池对象,内部存储了多个Connection对象
ComboPooledDataSource cpds = new ComboPooledDataSource();
//设置驱动类名
cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver
//设置数据库的连接地址
cpds.setJdbcUrl( "jdbc:mysql://127.0.0.1:3306/day02" );
//设置用户名
cpds.setUser("root");
//设置密码
cpds.setPassword("123456");
//连接池对象,调用getConnection方法
Connection con = cpds.getConnection();
System.out.println(con);
}
}
4.通过配置文件使用c3p0连接池
方式一:c3p0.properties配置文件
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/day01
c3p0.user=root
c3p0.password=root
package c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class Demo02 {
public static void main(String[] args) throws SQLException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
Connection con = cpds.getConnection();
System.out.println(con);
}
}
方式二:通过c3p0-config.xml文件
<c3p0-config>
<!-- 使用默认的配置读取连接池对象 -->
<default-config>
<!-- 连接参数 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day01</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 连接池参数 -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">10</property>
<property name="checkoutTimeout">2000</property>
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
package c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class Demo02 {
public static void main(String[] args) throws SQLException {
ComboPooledDataSource cpds = new ComboPooledDataSource();
Connection con = cpds.getConnection();
System.out.println(con);
}
}
5.c3p0连接池常用的配置参数: