如果每次操作数据库都需要重新连接数据库,那么会很浪费资源。因此建议使用数据库的连接池来满足多线程的数据库操作。

Java中数据库连接池有多种实现方法,推荐使用DBCP,这是Apache 提供的数据库连接池的实现。

在Maven中添加如下依赖:

    <dependency><groupId>org.apache.commons</groupId><artifactId>commons-dbcp2</artifactId><version>2.6.0</version></dependency>

注意:2.6.0版本是最新的版本,不支持低于Java8的版本,更多内容参考官方文档:DBCP – Overview


官方样例:

/** Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;//
// Here are the dbcp-specific classes.
// Note that they are only used in the setupDataSource
// method. In normal use, your classes interact
// only with the standard JDBC API
//
import org.apache.commons.pool2.ObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.dbcp2.ConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolingDataSource;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.DriverManagerConnectionFactory;//
// Here's a simple example of how to use the PoolingDataSource.
////
// Note that this example is very similar to the PoolingDriver
// example.  In fact, you could use the same pool in both a
// PoolingDriver and a PoolingDataSource
////
// To compile this example, you'll want:
//  * commons-pool2-2.3.jar
//  * commons-dbcp2-2.1.jar
// in your classpath.
//
// To run this example, you'll want:
//  * commons-pool2-2.3.jar
//  * commons-dbcp2-2.1.jar
//  * commons-logging-1.2.jar
//  * the classes for your (underlying) JDBC driver
// in your classpath.
//
// Invoke the class using two arguments:
//  * the connect string for your underlying JDBC driver
//  * the query you'd like to execute
// You'll also want to ensure your underlying JDBC driver
// is registered.  You can use the "jdbc.drivers"
// property to do this.
//
// For example:
//  java -Djdbc.drivers=org.h2.Driver \
//       -classpath commons-pool2-2.3.jar:commons-dbcp2-2.1.jar:commons-logging-1.2.jar:h2-1.3.152.jar:. \
//       PoolingDataSourceExample \
//       "jdbc:h2:~/test" \
//       "SELECT 1"
//
public class PoolingDataSourceExample {public static void main(String[] args) {//// First we load the underlying JDBC driver.// You need this if you don't use the jdbc.drivers// system property.//System.out.println("Loading underlying JDBC driver.");try {Class.forName("org.h2.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}System.out.println("Done.");//// Then, we set up the PoolingDataSource.// Normally this would be handled auto-magically by// an external configuration, but in this example we'll// do it manually.//System.out.println("Setting up data source.");DataSource dataSource = setupDataSource(args[0]);System.out.println("Done.");//// Now, we can use JDBC DataSource as we normally would.//Connection conn = null;Statement stmt = null;ResultSet rset = null;try {System.out.println("Creating connection.");conn = dataSource.getConnection();System.out.println("Creating statement.");stmt = conn.createStatement();System.out.println("Executing statement.");rset = stmt.executeQuery(args[1]);System.out.println("Results:");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();} finally {try { if (rset != null) rset.close(); } catch(Exception e) { }try { if (stmt != null) stmt.close(); } catch(Exception e) { }try { if (conn != null) conn.close(); } catch(Exception e) { }}}public static DataSource setupDataSource(String connectURI) {//// First, we'll create a ConnectionFactory that the// pool will use to create Connections.// We'll use the DriverManagerConnectionFactory,// using the connect string passed in the command line// arguments.//ConnectionFactory connectionFactory =new DriverManagerConnectionFactory(connectURI,null);//// Next we'll create the PoolableConnectionFactory, which wraps// the "real" Connections created by the ConnectionFactory with// the classes that implement the pooling functionality.//PoolableConnectionFactory poolableConnectionFactory =new PoolableConnectionFactory(connectionFactory, null);//// Now we'll need a ObjectPool that serves as the// actual pool of connections.//// We'll use a GenericObjectPool instance, although// any ObjectPool implementation will suffice.//ObjectPool<PoolableConnection> connectionPool =new GenericObjectPool<>(poolableConnectionFactory);// Set the factory's pool property to the owning poolpoolableConnectionFactory.setPool(connectionPool);//// Finally, we create the PoolingDriver itself,// passing in the object pool we created.//PoolingDataSource<PoolableConnection> dataSource =new PoolingDataSource<>(connectionPool);return dataSource;}
}

java使用数据库连接池连接MySQL/MariaDB--DBCP2相关推荐

  1. mysql事务锁导致tomcat崩溃_数据库连接池连接耗尽,导致tomcat请求无响应,呈现出假死状态...

    最困难的事情就是认识自己! 个人网站 ,欢迎访问! 前言:最近,测试部门的同事找到我,说他们测试时,没一会就发现服务接口请求一直无响应,Tomcat跟死掉了一样,也没有返回任何的错误响应,说让我赶紧排 ...

  2. mysql连接池和最大连接数_数据库连接池和mysql的最大连接数的区别

    什么叫做数据库连接池 连接池的作用是什么? 数据库连接池,简称dbcp database connection pool 存在意义: 数据库的连接是非常耗费系统资源的,一个应用通常都是需要与数据库打交 ...

  3. net core mysql 连接池_EF Core 小坑:DbContextPool 会引起数据库连接池连接耗尽

    EF Core 小坑:DbContextPool 会引起数据库连接池连接耗尽 发布时间:2019-02-18 22:05, 浏览次数:1152 , 标签: EF Core DbContextPool ...

  4. ef mysql 连接数_EF Core 小坑:DbContextPool 会引起数据库连接池连接耗尽

    原标题:EF Core 小坑:DbContextPool 会引起数据库连接池连接耗尽 DbContextPool 是 ASP.NET Core 2.1 引入的新特性,可以节省创建 DbContext ...

  5. Java jdbc数据库连接池

    1. 引言 近年来,随着Internet/Intranet建网技术的飞速发展和在世界范围内的迅速普及,计算机 应用程序已从传统的桌面应用转到Web应用.基于B/S(Browser/Server)架构的 ...

  6. centos中用C/C++语言连接MySQL/MariaDB数据库

    centos中用C/C++语言连接MySQL/MariaDB数据库 安装MariaDB 设置字符集(别管是什么,干就完事了) 设置远程链接MariaDB 上C语言 安装MariaDB yum inst ...

  7. 数据库连接池连接异常com.alibaba.druid.pool.GetConnectionTimeoutException

    数据库连接池连接异常com.alibaba.druid.pool.GetConnectionTimeoutException 参考文章: (1)数据库连接池连接异常com.alibaba.druid. ...

  8. Alibaba Druid 源码阅读(五)数据库连接池 连接关闭探索

    Alibaba Druid 源码阅读(五)数据库连接池 连接关闭探索 简介 在上文中探索了数据库连接池的获取,下面接着初步来探索下数据库连接的关闭,看看其中具体执行了那些操作 连接关闭 下面的具体的代 ...

  9. 在java中使用JDBC连接mysql数据库时的服务器时区值无法识别或表示多个时区的问题解决方案

    项目场景: 在java中使用JDBC连接mysql数据库时,报以下的错:Exception in thread "main" java.sql.SQLException: The ...

最新文章

  1. 前端开发工程师——网易云课堂
  2. Linux 安装Opencv3.2
  3. leetcode 54. Spiral Matrix | 54. 螺旋矩阵(Java)
  4. LeetCode 628. 三个数的最大乘积
  5. 800多名各国院士热忱参与 第三届“科学探索奖”名单公布
  6. 每日算法系列【LeetCode 16】最接近的三数之和
  7. c语言完整表白程序代码,C语言告白代码,一闪一闪亮晶晶~
  8. PS去掉图片上反光的操作流程
  9. 创建批处理文件.bat文件(删除指定文件夹下的文件及文件夹并循环)
  10. iOS IOS开发中各种型号的分辨率总结
  11. vue-loader was used without the corresponding plugin.
  12. 那,那,那,轻灵的舞影,绝美的身姿──对上古绚丽舞姿的乱谈
  13. 全球及中国空气净化器市场销售模式与营销策略前景咨询报告2022版
  14. 用批处理文件把.txt后缀的文件全部换成其他后缀文件
  15. 微信小程序解密失败的可能原因
  16. 车载冰箱E-mark认证测试项目有哪些?
  17. 邮件系统排名中企业邮箱有何优势,163邮箱能发国外邮件吗?
  18. [Numpy]stack(), hstack(), vstack(), concatenate()
  19. 快速识别图像的人工智能图像识别小程序分享
  20. 三相电开水器的工作原理及接法

热门文章

  1. dis的前缀单词有哪些_英语单词词根.词缀II 5个最高频英语前缀 必背
  2. Nature子刊:植物根系微生物组中共生细菌的宿主偏好性
  3. PNAS | 根际植保素合成调控细菌对植物的促生长作用
  4. html接收model数据,QAbstractTableModel数据返回要显示的html代码
  5. R语言数学函数:abs绝对值、sqrt平方根、ceiling向上近似整数、floor向下近似整数、trunc去除小数部分、round近似到指定小数位、signif近似到有效数字、三角函数、指数、对数
  6. seaborn可视化直方图(histogram)、添加密度曲线、并自定义直方图中每一个条形的条形框的色彩(edgecolor)
  7. R语言ggplot2可视化指定图像标题(title)、副标题(subtitle)的内容、字体大小、字体类型、色彩、对齐方式等实战
  8. R语言数据排序函数sort, order rank实战
  9. python计算特征的统计值并文本输出
  10. 异常检测概念、异常检测的思路、孤立森林Isolation Forest、​​​​​​​局部异常因子LOF、OneClassSVM、EllipticEnvelop