传统数据库连接的问题
- 普通的JDBC数据库连接使用DriverManager来获取,每次向数据库建立连接的时候都要将Connection加载到内存中,再验证用户名和密码。需要数据库连接的时候就要向数据库要求一个,执行完成后再断开连接。此方式会消耗大量的资源和时间。数据库连接的资源并没有得到很好的重复利用,若同时有多人在线,频繁地进行数据库连接操作将占用很多系统资源,严重时甚至会导致服务器奔溃。
- 对于每一次数据库连接,使用完后都得断开。否则,如果程序出现异常而未能关闭,将会导致数据库系统内存泄漏。
- 不能控制被创建的连接对象数,系统资源会毫无顾忌地分配出去,如果连接过多,会导致内存泄漏。
使用数据库连接池的好处
- 提高了程序地响应速度(减少了创建连接响应地时间)。
- 降低资源的消耗(可以重复使用已经提供好的连接)。
- 便于连接管理。
数据库连接池有以下几种方式:
C3P0:是一个开源组织提供的数据库连接池,速度相对较慢,稳定性还可以。Hibernate官方推荐使用。
DBCP:是Apache提供的数据库连接池。速度相对C3P0较快。但因自身bug,Hibernate3已经不再提供支持。
Druid:阿里提供的数据库连接池。
Proxool:是sourceforge下的一个开源项目数据库连接池,有监控连接池状态的功能,稳定性较C3P0差一点。
BoneCP:一个开源组织提供的数据库连接池,速度快。
C3P0
使用时需导入c3p0-0.9.1.2.jar。
获取数据库连接如下:
private static ComboPooledDataSource cpds = new ComboPooledDataSource("hellc3p0");
public static Connection getConnection() throws SQLException{
Connection conn = cpds.getConnection();
return conn;
}
其中,配置文件名为c3p0-config.xml,内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="hellc3p0">
<!-- 提供获取连接的4个基本信息 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 进行数据库连接池管理的基本信息 -->
<!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器申请的连接数 -->
<property name="acquireIncrement">5</property>
<!-- c3p0数据库连接池中初始化时的连接数 -->
<property name="initialPoolSize">10</property>
<!-- c3p0数据库连接池维护的最少连接数 -->
<property name="minPoolSize">10</property>
<!-- c3p0数据库连接池维护的最多的连接数 -->
<property name="maxPoolSize">100</property>
<!-- c3p0数据库连接池最多维护的Statement的个数 -->
<property name="maxStatements">50</property>
<!-- 每个连接中可以最多使用的Statement的个数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
DBCP
使用时需导入commons-dbcp-1.4.jar和commons-pool-1.5.5.jar
获取连接代码
private static DataSource source;
static{
try {
Properties pros = new Properties();
FileInputStream is = new FileInputStream(new File("src/dbcp.properties"));
pros.load(is);
source = BasicDataSourceFactory.createDataSource(pros);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws Exception{
Connection conn = source.getConnection();
return conn;
}
其中,配置文件dbcp.properties内容如下:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///test
username=root
password=root
initialSize=10
Druid
需要导入druid-1.1.10.jar
获取连接代码
private static DataSource source;
static{
try {
Properties pros = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("druid.properties");
pros.load(is);
source = DruidDataSourceFactory.createDataSource(pros);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException{
Connection conn = source.getConnection();
return conn;
}
其中配置文件druid.properties内容如下:
url=jdbc:mysql:///test
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
initialSize=10
maxActive=10