java c3p0代码实现

  a)下载jar包,总共需要两个包,c3p0-0.9.1.2.jar和MySQL-connector-java-5.0.4-bin.jar 

  b)创建工程将两个jar包导入,然后创建属性文件c3p0.properties(只能是这样的名字) 
  c)配置好c3p0.properties,其内容如下:

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://10.1.40.61:3306/test_bid_system?useUnicode=true&characterEncoding=utf8
c3p0.user=root
c3p0.password=root
c3p0.initialPoolSize=3
c3p0.minPoolSize=3
c3p0.maxPoolSize=15
c3p0.acquireIncrement=3
c3p0.maxIdleTime=1000
c3p0.acquireRetryAttempts=30
c3p0.acquireRetryDelay=1000
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

编码

  a)创建连接池类ConnectionPool.java

public class ConnectionPool {
private static ComboPooledDataSource ds;
private static ConnectionPool pool;
//私有的构造函数
private ConnectionPool(){
ds = new ComboPooledDataSource();
}
public static final ConnectionPool getInstance(){
if(pool == null){
pool = new ConnectionPool();
}
return pool;
}
//获取连接池中的连接
public synchronized final Connection getConnection(){
try {
Connection conn = ds.getConnection();
return conn;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

  b)创建测试类Test.java

public class Test {
/**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
ConnectionPool pool = ConnectionPool.getInstance();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = pool.getConnection();
ps = conn.prepareStatement("select * from bms_weekreport");
rs = ps.executeQuery();
rs.next();
System.out.println("userId:"+rs.getString("userId"));
System.out.println("使用线程池连接数据库!");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值