数据库连接池_c3p0_基本使用与数据库连接池_c3p0_配置演示
数据库连接池_c3p0_基本使用
c3p0:数据库连接池技术
步骤:导入jar包(两个)c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar,导包的时候不要忘记导入驱动jar包
2.定义配置文件:
名称: c3p0.properties 或者 c3p0-config.xml
路径:直接将文件放在src目录下即可
3.创建核心对象 数据库连接池对象 ComboPooledDateSource
4.获取连接:getConnction
package cn.xueqiang.datasource.c3p0; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * c3p0的演示 */ public class C3P0Demo1 { public static void main(String[] args) throws SQLException { //1.创建数据库连接池对象 DataSource ds = new ComboPooledDataSource(); //2. 获取连接对象 Connection conn = ds.getConnection(); //3. 打印 System.out.println(conn); } }
数据库连接池_c3p0_配置演示
package cn.xueqiang.datasource.c3p0; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * c3p0演示 */ public class C3P0Demo2 { public static void main(String[] args) throws SQLException { //1.获取DataSource DataSource ds = new ComboPooledDataSource(); //2.获取连接 for (int i = 1; i <= 10; i++) { Connection conn = ds.getConnection(); System.out.println(i+":"+conn); } } }
显示 An attempt by a client to checkout a Connection has timed out.(客户端尝试签出连接已超时)如果超过最大的连接数就会报错他会等待三秒
public static void testNameConfig() throws SQLException { //1.1.获取DataSource,使用指定名称配置 DataSource dataSource = new ComboPooledDataSource("otherc3p0"); //2.获取连接 for (int i = 1; i <= 10; i++) { Connection conn = dataSource.getConnection(); System.out.println(i + ":" + conn); } } }