数据库连接池
为数据库建立一个缓冲池,与现在缓冲池中放一定数量的数据库连接,当需要使用连接时,从缓冲池中拿出一个使用,使用完毕后再放回去,其允许应用程序重复的使用一个数据库连接,而并不是不断的进行创建和关闭。
数据库连接池负责分配、管理和释放连接。
C3P0
JDBCutils.java中对数据库连接池的使用,使用c3p0对创建数据库连接再进行操作。
public class JDBCUtils {
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">
<!-- 四个数据库连接的基本信息 -->
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test?Unicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true</property>
<property name="user">root</property>
<property name="password">123456</property>
<!-- 当连接池中的连接不够时,一次添加多少 -->
<property name="acquireIncrement">5</property>
<!-- c3p0初始化时的连接数 -->
<property name="initialPoolSize">10</property>
<!-- 最小的连接数 -->
<property name="minPoolSize">10</property>
<!-- 最大的连接数 -->
<property name="maxPoolSize">100</property>
<!-- 总共维护的最多的Statement数目 -->
<property name="maxStatements">50</property>
<!-- 对于每一个连接,维护的最大Statement数目 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
DBCP
配置文件:dbcp.properties
//必要信息
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?Unicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=123456
initialSize=10 //初始大小
JDBCUtils.java中dbcp连接池获取连接:
private static DataSource source;
{
try {
Properties pros = new Properties();
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("dbcp.prpperties");
pros.load(is);
source = BasicDataSourceFactory.createDataSource(pros);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection2() throws Exception{
Connection conn = source.getConnection();
return conn;
}
Druid
Druid是最常用的数据库连接池,其继承了C3P0、DBCP以及Prooval的优点
Druid.properties:
url=jdbc:mysql://localhost:3306/test?Unicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
password=123456
driveClassName=com.mysql.cj.jdbc.Driver
initialSize=10
maxActive=10
JDBCUtils.java:
private DataSource source1;
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 getConnection3() throws SQLException {
Connection conn = source.getConnection();
return conn;
}