C3P0连接池
public class C3P0_ {
public void testC3P0_01() throws Exception {
// 创建一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
// 给数据源设置相关参数
// 连接管理是由comboPooledDataSource来管理
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
comboPooledDataSource.setJdbcUrl(url);
// 设置初始化链接数
comboPooledDataSource.setInitialPoolSize(10);// 初始化为10个,不够再扩容
comboPooledDataSource.setMaxPoolSize(50);// 最大设置50个,超过50就排队等待
// 获取链接
Connection connection = comboPooledDataSource.getConnection();
// 关闭链接
connection.close();
}
// 使用配置文件模板
// 将xml文件拷贝到src目录
public void test_02() throws Exception {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("ybj_edu");
Connection connection = comboPooledDataSource.getConnection();
connection.close();
}
}
- 配置文件
<c3p0-config>
<named-config name="ybj_edu">
<!-- 驱动类 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<!-- url-->
<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/host</property>
<!-- 用户名 -->
<property name="user">root</property>
<!-- 密码 -->
<property name="ybj">root</property>
<!-- 每次增长的连接数-->
<property name="acquireIncrement">5</property>
<!-- 初始的连接数 -->
<property name="initialPoolSize">10</property>
<!-- 最小连接数 -->
<property name="minPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">10</property>
<!-- 可连接的最多的命令对象数 -->
<property name="maxStatements">5</property>
<!-- 每个连接对象可连接的最多的命令对象数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
德鲁伊连接池
public class Druid_ {
public void testDruid() throws Exception{
// 加入Druid jar包
// 加入配置文件druid_properties
// 创建Properties
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
//创建一个指定参数的数据库连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
connection.close();
}
}
- druid_properties配置文件
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/root?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/girls
username=root
password=ybj
#initial connection Size
initialSize=10
#min idle connection size
minIdle=5
#max active connection size
maxActive=20
#max wait time (5000 mil seconds)
maxWait=5000