首先下载c3p0的jar包
https://mvnrepository.com/search?q=c3p0
导入jar包到eclipse
将c3p0的jar包放到eclipse中,单击右键,选择build path ,在选择 add jars
创建连接池对象
ComboPooledDataSource cpd= new ComboPooledDataSource();
设置连接参数
方法一
使用静态代码块来初始化参数(不推荐)如果数据库发生改变,源文件需要重新编写编译,项目需要重新部署
1
2
3
4
5
6
7
8
9
10
11
12
|
static ComboPooledDataSource cpd= new ComboPooledDataSource(); static { try { cpd.setDriverClass( "com.mysql.jdbc.Driver" ); cpd.setJdbcUrl( "jdbc:mysql:///users?characterEnconding=utf-8" ); cpd.setUser( "root" ); cpd.setPassword( "123456" ); } catch (PropertyVetoException e) { // TODO Auto-generated catch block e.printStackTrace(); } } |
方法二
在src的目录下建立c3p0.propertise文件
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql:///users?characterEnconding=utf-8
c3p0.user=root
c3p0.password=123456
方法三
在src目录下建立 c3po-config.xml文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<? xml version = "1.0" encoding = "UTF-8" ?> < c3p0-config > < default-config > < property name = "driverClass" >com.mysql.jdbc.Driver </ property > < property name = "jdbcUrl" >jdbc:mysql:///jt_db?characterEncoding=utf-8 </ property > < property name = "user" >root </ property > < property name = "password" >root </ property > </ default-config > </ c3p0-config > |
调用连接池对象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//创建连接池对象 ComboPooledDataSource cpd= new ComboPooledDataSource(); public void find() throws Exception { //获取连接池连接 Connection conn = cpd.getConnection(); //创建传输器 PreparedStatement ps = conn.prepareStatement( "select * from user" ); //结果集 ResultSet rs = ps.executeQuery(); while (rs.next()) { rs.getInt( 1 ); //获取的行的第一列 rs.getString( "id" ); //获取行的id列 } } |
连接池对象的close方发被改造了,不是释放连接而是将连接还给连接池
rs.close();
ps.close();
conn.close();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://www.cnblogs.com/syrgdm/p/13220768.html