首先下載c3p0的jar包
https://mvnrepository.com/search?q=c3p0
導入jar包到eclipse
將c3p0的jar包放到eclipse中,單擊右鍵,選擇build path ,在選擇 add jars
創(chuàng)建連接池對象
ComboPooledDataSource cpd= new ComboPooledDataSource();
設置連接參數(shù)
方法一
使用靜態(tài)代碼塊來初始化參數(shù)(不推薦)如果數(shù)據(jù)庫發(fā)生改變,源文件需要重新編寫編譯,項目需要重新部署
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 > |
調(diào)用連接池對象
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//創(chuàng)建連接池對象 ComboPooledDataSource cpd= new ComboPooledDataSource(); public void find() throws Exception { //獲取連接池連接 Connection conn = cpd.getConnection(); //創(chuàng)建傳輸器 PreparedStatement ps = conn.prepareStatement( "select * from user" ); //結果集 ResultSet rs = ps.executeQuery(); while (rs.next()) { rs.getInt( 1 ); //獲取的行的第一列 rs.getString( "id" ); //獲取行的id列 } } |
連接池對象的close方發(fā)被改造了,不是釋放連接而是將連接還給連接池
rs.close();
ps.close();
conn.close();
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/syrgdm/p/13220768.html