依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>yofc</groupId>
<artifactId>jdbc</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.4.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies> <build>
<plugins>
<!-- 指定jdk -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

获取连接,三种方式

1、BasicDataSource

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.jupiter.api.Test; import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties; public class DBCPTest {
@Test
public void testDBCP() throws SQLException {
BasicDataSource dataSource = new BasicDataSource(); // 设置必须属性
dataSource.setUsername("root");
dataSource.setPassword("root");
dataSource.setUrl("jdbc:mysql://192.168.8.136:3306/jdbc");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 设置可选属性 // 指定数据库连接池中初始化连接数的个数
dataSource.setInitialSize(5);
// 指定最大的连接数: 同一时刻可以同时向数据库申请的连接数
dataSource.setMaxTotal(5);
// 指定小连接数: 在数据库连接池中保存的最少的空闲连接的数量
dataSource.setMinIdle(2);
// 等待数据库连接池分配连接的最长时间. 单位为毫秒. 超出该时间将抛出异常.
dataSource.setMaxWaitMillis(1000 * 5); // 从数据源中获取数据库连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close(); printDataSourceStats(dataSource);
shutdownDataSource(dataSource);
} private static void printDataSourceStats(DataSource ds) {
BasicDataSource bds = (BasicDataSource) ds;
System.out.println("NumActive: " + bds.getNumActive());
System.out.println("NumIdle: " + bds.getNumIdle());
} private static void shutdownDataSource(DataSource ds) throws SQLException {
BasicDataSource bds = (BasicDataSource) ds;
bds.close();
}
}

配置文件方式

dbcp.properties

username=root
password=root
url=jdbc:mysql://192.168.8.136:3306/jdbc
driverClassName=com.mysql.cj.jdbc.Driver initialSize=10
maxTotal=50
minIdle=5
maxWaitMillis=5000
@Test
public void testDBCPWithConfig() throws Exception {
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties = new Properties();
properties.load(inStream);
BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties); // 从数据源中获取数据库连接
System.out.println(dataSource.getConnection()); printDataSourceStats(dataSource);
shutdownDataSource(dataSource);
}

2、PoolingDataSource

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool; import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class PoolingDataSourceExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rset = null; try {
Class.forName("com.mysql.cj.jdbc.Driver");
DataSource dataSource = setupDataSource("jdbc:mysql://192.168.8.136:3306/jdbc"); conn = dataSource.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery("select * from user");
int numcols = rset.getMetaData().getColumnCount();
while (rset.next()) {
for (int i = 1; i <= numcols; i++) {
System.out.print("\t" + rset.getString(i));
}
System.out.println("");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rset != null) rset.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
}
}
} public static DataSource setupDataSource(String connectURI) {
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, "root", "root");
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
poolableConnectionFactory.setPool(connectionPool); PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<>(connectionPool);
return dataSource;
}
}

3、PoolingDriver

import org.apache.commons.dbcp2.*;
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool; import java.sql.*; public class PoolingDriverExample {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rset = null; try {
Class.forName("com.mysql.cj.jdbc.Driver");
setupDriver("jdbc:mysql://192.168.8.136:3306/jdbc");
conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example");
stmt = conn.createStatement();
rset = stmt.executeQuery("select * from user");
int numcols = rset.getMetaData().getColumnCount();
while (rset.next()) {
for (int i = 1; i <= numcols; i++) {
System.out.print("\t" + rset.getString(i));
}
System.out.println("");
}
printDriverStats();
shutdownDriver();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rset != null) rset.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
}
}
} public static void setupDriver(String connectURI) throws Exception {
ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, "root", "root");
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
poolableConnectionFactory.setPool(connectionPool); Class.forName("org.apache.commons.dbcp2.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool("example", connectionPool);
} public static void printDriverStats() throws Exception {
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
ObjectPool<? extends Connection> connectionPool = driver.getConnectionPool("example");
System.out.println("NumActive: " + connectionPool.getNumActive());
System.out.println("NumIdle: " + connectionPool.getNumIdle());
} public static void shutdownDriver() throws Exception {
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.closePool("example");
}
}

官方文档

http://www.cnblogs.com/wang-meng/p/5463020.html

JDBC-DBCP的更多相关文章

  1. java jdbc dbcp连接SQL Server

    使用到的jar: commons-collections-3.1.jar commons-dbcp-1.4.jar commons-pool-1.5.6.jar sqljdbc4.jar dbcp配置 ...

  2. c3p0;jdbc;dbcp;mybatis;ubutils;

    [说明]今天还是完成了一定东西的,上午是jdbc的测试,下午是 数据库连接池 和 dbutils 的测试,晚上是mybatis的测试,都是找了一些网上的例子运行了一下,解决出现的问题. 一:今日完成 ...

  3. initialSize,maxTotal,maxIdle,minIdle,maxWaitMillis

    初始化连接数:默认值 0 同一时刻可分配最大连接数:默认值 8 ,设置为负数时不做限制 最大空闲连接,默认值 8 ,超出连接将被释放 最小空闲连接数,默认值 0 请求连接最大等待时间(毫秒),默认值 ...

  4. SSH登录与增删改查demo详解+源代码

    点击下载,测试绝对可用SSH整合框架登录加增删改查demo 下载地址:http://download.csdn.net/detail/qq_33599520/9784679   一.框架概述 spri ...

  5. ssm+redis整合(通过cache方式)

    这几天的研究ssm redis 终于进入主题了,今天参考了网上一些文章搭建了一下ssm+redis整合,特别记录下来以便以后可以查询使用,有什么不足请大牛们提点 项目架构 1.pom.xml < ...

  6. ssm 整合(方案二 maven)

    通过maven来整合ssm方便很多,至少不用去找jar包 具体架构如下: 1.配置pom.xml <project xmlns="http://maven.apache.org/POM ...

  7. ssm整合(方案一 引入jar)

    最近为了研究redis整合,基本都是ssm+redis 好吧 我是老古董了,以前都是ssi,那就折腾一下ssm先,具体方案: 方案一:基本引入jar版.方案二:maven版(后续继续整) 这篇主要是通 ...

  8. SSM项目的数据库密码加密方案

    项目主要采用:SpringMVC4.3.2.RELEASE +Spring4.3.2.RELEASE + Maven 3.3.3 + druid 1.0.29 + Mybatis 3.2.8 + My ...

  9. 杂谈spring、springMVC

    一.背景 目前项目组都在用SSM(spring+springMVC+mybatis)开发项目 大家基本都停留在框架的基本使用阶段,对框架的职责并不清晰,导致配置文件出现了不少问题 在这简单讲解一下sp ...

  10. Eclipse+Tomcat7.0+MySQL 连接池设置

    http://blog.sina.com.cn/s/blog_85d71fb70101ab99.html 工程名:JavaWeb 第一步:配置server.xml 在Tomcat的server.xml ...

随机推荐

  1. Typora——安装Pandoc

    安装 打开typora,帮助-> Install and Use Pandoc  |  访问在线地址 https://support.typora.io/Install-and-Use-Pand ...

  2. 网页调起QQ聊天

    将QQ账号换成正常的QQ号即可,要确保这个QQ支持临时会话 <a href="http://wpa.qq.com/msgrd?v=3&uin=QQ账号&site=qq& ...

  3. 【BZOJ3379】【USACO2004】交作业 区间DP

    题目描述 数轴上有\(n\)个点,你要从位置\(0\)去位置\(B\),你每秒钟可以移动\(1\)单位.还有\(m\)个限制,每个限制\((x,y)\)表示你要在第\(t\)秒之后(可以是第\(t\) ...

  4. 【题解】 bzoj2982: combination (Lucas定理)

    题面戳我 Solution 板子题 Code //It is coded by ning_mew on 7.25 #include<bits/stdc++.h> #define LL lo ...

  5. BZOJ 2521: [Shoi2010]最小生成树(最小割)

    题意 对于某一条无向图中的指定边 \((a, b)\) , 求出至少需要多少次操作.可以保证 \((a, b)\) 边在这个无向图的最小生成树中. 一次操作指: 先选择一条图中的边 \((u, v)\ ...

  6. Android GPS定位测试(附效果图)

    今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整 ...

  7. [复习]莫比乌斯反演,杜教筛,min_25筛

    [复习]莫比乌斯反演,杜教筛,min_25筛 莫比乌斯反演 做题的时候的常用形式: \[\begin{aligned}g(n)&=\sum_{n|d}f(d)\\f(n)&=\sum_ ...

  8. 【BZOJ5197】Gambling Guide (最短路,期望)

    [BZOJ5197]Gambling Guide (最短路,期望) 题面 BZOJ权限题 洛谷 题解 假设我们求出了每个点的期望,那么对于一个点,只有向期望更小的点移动的时候才会更新答案. 即转移是: ...

  9. 【Linux】linux正则表达式及通配符

    正则表达式就是用于匹配每行输入的一种模式,模式是指一串字符序列.拥有强大的字符搜索功能.也非常方便的搜索过滤出我们想要的内容. linux正则表达式分为基本正则表达式(Basic Regexp)和扩展 ...

  10. CF1131E String Multiplication(???)

    这题难度2200,应该值了. 题目链接:CF原网 题目大意:定义两个字符串 $s$ 和 $t$($s$ 的长度为 $m$)的乘积为 $t+s_1+t+s_2+\dots+t+s_m+t$.定义一个字符 ...