JDBC学习笔记(cp30数据库连接池)

版权声明:转载请说明去处,文章仅供学习参考 https://blog.csdn.net/qq_38487155/article/details/82529821

c3p0数据库连接池

使用前必须导入:mysql-connector-java-5.1.7-bin.jar,c3p0-0.9.2-pre1.jar和

                             mchange-commons-0.2.jar 三个jar包, 

                             c3p0-oracle-thin-extras-0.9.2-pre1.jar(使用oracle需要导入)

1、代码配置

		//代码配置
		ComboPooledDataSource ds = new ComboPooledDataSource();
		ds.setDriverClass("com.mysql.jdbc.Driver");
		ds.setJdbcUrl("jdbc:mysql://localhost:3306/test");	
		ds.setUser("root");
		ds.setPassword("123456");
		
		//设置连接每次增量为5		
		ds.setAcquireIncrement(5) ;
		
		//设置初始化连接数量20
		ds.setInitialPoolSize(20) ;
		
		//设置最小连接数2
		ds.setMinPoolSize(2) ;
		
		//设置最大连接数50
		ds.setMaxPoolSize(50) ;
				
		Connection con = ds.getConnection();
		System.out.println(con);

2、配置文件配置

 配置文件要求:

c3p0-config.xml配置文件如下图所示: 

  • 文件名称:必须叫c3p0-config.xml
  • 文件位置:必须在src下
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
	<!-- 默认配置,当使用ComboPooledDataSource无参构造器时,使用的就是这个配置 -->
	<default-config>
		<!-- 基本配置 -->
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<!-- 每次增量,当需要创建Connection对象时,一次创建几个 -->
		<property name="acquireIncrement">3</property>
		<!-- 当创建池对象后,池中应该有几个Connection对象 -->
		<property name="initialPoolSize">10</property>
		<!-- 池中最少Connection个数,如果少于这个值,就会创建Connection -->
		<property name="minPoolSize">2</property>
		<!-- 池中最大连接个数 -->
		<property name="maxPoolSize">10</property>
	</default-config>
	<!-- 命名配置,new ComboPooledDataSource("oralce-config")时,使用的就是这个配置 -->
	<named-config name="oracle-config">
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/mydb1</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">123</property>
		<property name="acquireIncrement">3</property>
		<property name="initialPoolSize">10</property>
		<property name="minPoolSize">2</property>
		<property name="maxPoolSize">10</property>
	</named-config>
</c3p0-config>

 只用三行代码就可获取连接

		//配置文件配置
		ComboPooledDataSource ds = new ComboPooledDataSource();
		Connection connection=ds.getConnection();
		System.out.println(connection);

猜你喜欢

转载自blog.csdn.net/qq_38487155/article/details/82529821
今日推荐