簡介:
commons-dbcp工具包是用來提供數據庫連接池服務.
話不多說,奉上使用方法:
①引入maven依賴
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
②測試代碼
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
public class DBCPTest {
public void init() throws Exception {
Properties p = new Properties();
p.setProperty("driverClassName", "com.mysql.jdbc.Driver");
p.setProperty("url", "jdbc:mysql://localhost:3306/test");
p.setProperty("username", "root");
p.setProperty("password", "root");
p.setProperty("maxActive", "50");// 設置最大併發數
p.setProperty("initialSize", "20");// 數據庫初始化時,創建的連接個數
p.setProperty("minIdle", "10");// 最小空閒連接數
p.setProperty("maxIdle", "10");// 數據庫最大連接數
p.setProperty("maxWait", "1000");// 超時等待時間(毫秒)
p.setProperty("removeAbandoned", "false");// 是否自動回收超時連接
p.setProperty("removeAbandonedTimeout", "120");// 超時時間(秒)
p.setProperty("testOnBorrow", "true");// 取得連接時進行有效性驗證
p.setProperty("logAbandoned", "true");// 是否在自動回收超時連接的時候打印連接的超時錯誤
BasicDataSource dataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(p);
Connection connection = dataSource.getConnection();
}
public void init2() throws SQLException {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/test");
dataSource.setUsername("root");
dataSource.setPassword("root");
Connection connection = dataSource.getConnection();
}
}