14.连接池.md
连接池定义
使用统一的规范:javax.sql.DataSource实现统一编程
常用开源连接池:
- DBCP:tomcat
- C3P0:hibernate
DBCP:
核心类::核心类BasicDataSource
Demo:
package per.liyue.code.connectionpool;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.junit.Test;
public class DbcpDemo {
@Test
public void Demo1() throws Exception{
/*
* 硬编码形式实现:核心类BasicDataSource
*/
BasicDataSource db = new BasicDataSource();
db.setUrl("jdbc:mysql:///hi"); //数据库连接字符串
db.setDriverClassName("com.mysql.jdbc.Driver"); //驱动
db.setUsername("root"); //用户名
db.setPassword("root"); //密码
db.setInitialSize(3); //初始化连接
db.setMaxActive(6); //最大连接
db.setMaxIdle(3000); //最大空闲时间
Connection conn = db.getConnection();
conn.prepareStatement("show tables").execute();
conn.close();
/*
* 配置文件实现
*/
//加载配置文件
Properties prop = new Properties();
//获取文件信息
InputStream inStream = DbcpDemo.class.getResourceAsStream("mydbcp.properties");
prop.load(inStream);
//根据配置创建数据源对象
DataSource dbProp = BasicDataSourceFactory.createDataSource(prop);
//获取连接
Connection connProp = db.getConnection();
connProp.prepareStatement("show tables").execute();
connProp.close();
//关闭
}
}
C3P0
核心类:ComboPooledDataSource
//...
//硬编码方式:
ComboPooledDataSource dbC3P0 = new ComboPooledDataSource();
// ...
/*
* 自动加载src下的xml文件:c3p0-config.xml
*/
ComboPooledDataSource dbC3P0 = new ComboPooledDataSource();