C3P0数据库连接池实现

C3P0数据库连接池实现

使用的包c3p0-0.9.1.2.jar

方式一:

	//方式一:
	@Test
	public void testGetConnection() throws Exception{
		//获取C3P0数据库连接池
		ComboPooledDataSource cpds = new ComboPooledDataSource();
		cpds.setDriverClass( "com.mysql.jdbc.Driver" ); //loads the jdbc driver            
		cpds.setJdbcUrl( "jdbc:mysql://localhost:3306/test" );
		cpds.setUser("root");                                  
		cpds.setPassword("root");
		//通过设置相关的参数,对数据库连接池进行管理
		//设置初始时数据库连接池中的连接数
		cpds.setInitialPoolSize(10);
		
		Connection connection = cpds.getConnection();
		System.out.println(connection);
		
		//销毁c3p0数据库连接池(谨慎使用!!!!!!)
		DataSources.destroy(cpds);
	}

方式二:使用配置文件

  1. src目录下创建c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

	<named-config name="helloc3p0">
		<!-- 提供获取链接的4个基本信息 -->
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<!-- 默认地址为localhost:3306 可以省略-->
		<property name="jdbcUrl">jdbc:mysql:///test</property>
		<property name="user">root</property>
		<property name="password">root</property>
		
		<!-- 进行数据库连接池管理的基本信息 -->
		<!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器申请的连接数 -->
		<property name="acquireIncrement">5</property>
		<!-- c3p0数据库连接池中初始化时的连接数 -->
		<property name="initialPoolSize">10</property>
		<!-- c3p0数据库连接池维护的最少连接数 -->
		<property name="minPoolSize">10</property>
		<!-- c3p0数据库连接池维护的最多连接数 -->
		<property name="maxPoolSize">100</property>

		<!-- c3p0数据库连接池最多维护的 Statement 的个数 -->
		<property name="maxStatements">0</property>
		<!-- 每个连接中可以最多使用的 Statement 的个数 -->
		<property name="maxStatementsPerConnection">5</property>

	</named-config>
</c3p0-config>
  1. java
	//方式二:使用配置文件
	@Test
	public void testGetConnection1() throws Exception{
		ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0"); 
		Connection conn = cpds.getConnection();
		System.out.println(conn);
	}

JDBCUtils中使用C3P0数据库连接技术获取连接

package com.sammery.util;

import java.sql.Connection;
import java.sql.SQLException;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCUtils {
	/*
	 * 使用C3P0的数据库连接池技术
	 * */
	//防止每次调用都创建一个数据库连接池
	private static ComboPooledDataSource cpds = new ComboPooledDataSource("helloc3p0"); 
	
	public Connection getConnection() throws SQLException{
		Connection conn = cpds.getConnection();
		return conn;
	}
}

jar包链接:https://pan.baidu.com/s/1dgp_wfBmwc3ZkZ3UuPRv3Q
提取码:5r64

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值