为什么要用连接池呢?
- 在不使用连接池的系统中,每次用户请求数据库操作时我们都需要向数据库获取连接,而数据库创建连接需要消耗想对较大的资源,创建的时间也较长,如果我们一天的访问量有10w,那我们就需要10W的数据库连接,这是极大的系统资源浪费,极易造成数据库内存的溢出。
- 创建时间也比较长
- 造成数据库服务器的宕机
使用连接池的情况 - 一开始我们会创建一个容器,里面存放数据库的连接,用户访问时从容器中获取连接,用完后将连接释放。这样就对之前的情况起到一定程度的优化的效果。
使用c3p0连接池
首先我们需要先导入c3p0的包。
使用c3p0有两种方式接下来我会逐一的介绍。
常规方式配置连接池
public static void demo1() throws PropertyVetoException {
//创建连接
ComboPooledDataSource dataSource = new ComboPooledDataSource();
//设置连接池相关的参数
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/moocszh");
dataSource.setUser("root");
dataSource.setPassword("root");
dataSource.setMaxPoolSize(40);
//获得连接
Connection conn = null;
PreparedStatement pstmt=null;
ResultSet rs = null;
try {//获得连接
conn = dataSource.getConnection();
String sql = "select * from goods";
pstmt = conn.prepareStatement(sql);
//执行sql
rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getInt("id")+rs.getString("goods")+rs.getInt("price")+rs.getString("desp"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
Jdbc_util.release(rs,conn,pstmt);
}
}
我们首先要加载ComboPooledDataSource这个连接池的驱动器。
我们通过ComboPooledDataSource建立对数据库的连接,并且可以设置这个连接线程的
各种参数。
在这里本文除了设置了连接数据库的必要参数外还设置了dataSource.setMaxPoolSize(40);最大连接池数量这个参数。
运行后
1手机2000黑色,32G
2冰箱1500银色对开门
3洗衣机3000滚筒
4空调4000变频空调
5PS4PRO30001T
第二种配置方式可以通过写配置文件这种简单的方式来填写c3p0的配置参数,首先在类目录下创建名为c3p0_config.xml的文件,在文件我们的配置的参数为:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">root</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/moocszh</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>
然后我们在我们的dome中直接加载ComboPooledDataSource,然后运行如下代码:
public static void demo2() throws PropertyVetoException {
//获得连接
Connection conn = null;
PreparedStatement pstmt=null;
ResultSet rs = null;
try {//获得连接
ComboPooledDataSource dataSource = new ComboPooledDataSource();
conn = dataSource.getConnection();
String sql = "select * from goods";
pstmt = conn.prepareStatement(sql);
//执行sql
rs = pstmt.executeQuery();
while (rs.next()){
System.out.println(rs.getInt("id")+rs.getString("goods")+rs.getInt("price")+rs.getString("desp"));
}
} catch (Exception e) {
e.printStackTrace();
}finally {
Jdbc_util.release(rs,conn,pstmt);
}
}
执行结果为
1手机2000黑色,32G
2冰箱1500银色对开门
3洗衣机3000滚筒
4空调4000变频空调
5PS4PRO30001T
以上就是两种c3p0的两种处理方式。