思考:
程序中连接如何管理?
1.连接资源宝贵;需要对连接管理
2.连接:
a)操作数据库,创建连接
b)操作结束, 关闭!
分析:
涉及频繁的连接的打开、关闭,影响程序的运行效率!
连接管理:
预先创建一组连接,有的时候每次取出一个; 用完后,放回;
学习连接池:
a.自定义一个连接池
b.学习优秀的连接池组件
a)DBCP
b)C3P0
开源的连接池技术
概述:
Sun公司约定: 如果是连接池技术,需要实现一个接口!
javax.sql.DataSource;
连接池:
DBCP
C3P0
使用C3P0的步骤
1、导入 c3p0-0.9.1.2.jar
2、配置c3p0-config.xml
<c3p0-config>
<default-config>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo
</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="user">root</property>
<property name="password">root</property>
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize">3</property>
<!--连接池中保留的最大连接数。Default: 6 -->
<property name="maxPoolSize">6</property>
<!--最大空闲时间,1000秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime">1000</property>
</default-config>
</c3p0-config>
3、XML配置方式,使用C3P0连接池管理连接
// 创建c3p0连接池核心工具类
// 自动加载src下c3p0的配置文件【c3p0-config.xml】
ComboPooledDataSource dataSource = new ComboPooledDataSource();// 使用默认的配置
PreparedStatement pstmt = null;
// 获取连接
Connection con = dataSource.getConnection();
for (int i=1; i<11;i++){
String sql = "insert into employee(empName,dept_id) values(?,?)";
// 执行更新
pstmt = con.prepareStatement(sql);
pstmt.setString(1, "Rose" + i);
pstmt.setInt(2, 1);
pstmt.executeUpdate();
}
pstmt.close();
// 关闭
con.close();
工具类 DbUtiles
/**
*
* 1. 初始化C3P0连接池
* 2. 创建DbUtils核心工具类对象
* @author albin
*
*/
public class JdbcUtils {
/**
* 1. 初始化C3P0连接池
*/
private static DataSource dataSource;
static {
dataSource = new ComboPooledDataSource();
}
/**
* 2. 创建DbUtils核心工具类对象
*/
public static QueryRunner getQueryRuner(){
// 创建QueryRunner对象,传入连接池对象
// 在创建QueryRunner对象的时候,如果传入了数据源对象;
// 那么在使用QueryRunner对象方法的时候,就不需要传入连接对象;
// 会自动从数据源中获取连接(不用关闭连接)
return new QueryRunner(dataSource);
}
}