jdbc连接池的做用和用法说明

我们都知道通过jdbc 的链接 会消耗大量的连接,每一次连接都会消耗资源,关闭》打开都是要消耗资源的,频繁的建立、关闭连接,会极大的减低系统的性能,因为对于连接的使用成了系统性能的瓶颈。

数据库连接池技术带来的优势

1. 资源重用

2. 更快的系统响应速度

3. 新的资源分配手段

4. 统一的连接管理,避免数据库连接泄漏

原理图解

æ°æ®åºè¿æ¥æ± çå®ç°ååç

使用过程:

jdbc.properties

DriverClass = com.mysql.jdbc.Driver
JdbcUrl = jdbc\:mysql\://ID\:3306/htmldata?useUnicode\=true&characterEncoding\=UTF-8
User = root
Password = 123
MaxPoolSize = 20
MinPoolSize = 2
InitialPoolSize = 5
MaxStatements = 30
MaxIdleTime =100

C3P0Mysql.java

package class_name;
import java.sql.Connection;
import java.util.Properties;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Mysql {
	private ComboPooledDataSource cpds;
	private static C3P0Mysql c3P0Properties;
	static{
		c3P0Properties = new C3P0Mysql();
	}
	public C3P0Mysql() {
		try {
			cpds = new ComboPooledDataSource();
			
			//加载配置文件
			Properties props = new Properties();
			props.load(C3P0Mysql.class.getClassLoader().getResourceAsStream("jdbc.properties"));
			cpds.setDriverClass(props.getProperty("DriverClass"));
			cpds.setJdbcUrl(props.getProperty("JdbcUrl"));
			cpds.setUser(props.getProperty("User"));
			cpds.setPassword(props.getProperty("Password"));
			cpds.setMaxPoolSize(Integer.parseInt(props.getProperty("MaxPoolSize")));
			cpds.setMinPoolSize(Integer.parseInt(props.getProperty("MinPoolSize")));
			cpds.setInitialPoolSize(Integer.parseInt(props.getProperty("InitialPoolSize")));
			cpds.setMaxStatements(Integer.parseInt(props.getProperty("MaxStatements")));
			cpds.setMaxIdleTime(Integer.parseInt(props.getProperty("MaxIdleTime")));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static C3P0Mysql getInstance(){
		return c3P0Properties;
	}
	
	public Connection getConnection(){
		Connection conn = null;
		try {
			conn = cpds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Connection connection = C3P0Mysql.c3P0Properties.getConnection();
		System.out.println("已经连接成功");
	}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

加金开发

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值