JDBC Part5 DataSource 连接池操作

- javax.sql.DataSource 接口,通常由服务器实现

- DBCP  Tomcat自带相对C3P0速度较快,但存在BUG,已经不更新了

- Proxool  没听过、能监控连接池状态,稳定性差

- C3P0  速度较慢,但是稳定

- Druid  阿里巴巴提供,集成上面的所有优点,

- Hikari  目前最快的连接池依赖,据说有安全问题。。。

DataSource被称为数据源,包含连接池和连接池管理2部分


C3P0实现

官方文档:  https://blog.csdn.net/wangwei_cq/article/details/8930667

Maven依赖

  1. <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
  2. <dependency>
  3. <groupId>com.mchange</groupId>
  4. <artifactId>c3p0</artifactId>
  5. <version>0.9.5.5</version>
  6. </dependency>

第一种,硬编码的连接池

  1. package connector;
  2.  
  3. import com.mchange.v2.c3p0.ComboPooledDataSource;
  4. import org.junit.Test;
  5.  
  6. import java.beans.PropertyVetoException;
  7. import java.sql.Connection;
  8. import java.sql.SQLException;
  9.  
  10. /**
  11. * @author ArkD42
  12. * @file Jdbc
  13. * @create 2020 - 04 - 24 - 17:49
  14. */
  15. public class C3P0Test {
  16.  
  17. @Test
  18. public void dataSourceByC3p0() throws PropertyVetoException, SQLException {
  19. // 获取池对象
  20. ComboPooledDataSource dataSource = new ComboPooledDataSource();
  21. // 配置连接信息
  22. dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
  23. dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=Asia/Shanghai");
  24. dataSource.setUser("root");
  25. dataSource.setPassword("123456");
  26. //设置初始的连接数
  27. dataSource.setInitialPoolSize(10);
  28. //获取连接
  29. Connection connection = dataSource.getConnection();
  30. System.out.println(connection);
  31. }
  32. }

测试结果

第二种 XML配置文件

配置XML配置文件的信息

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <c3p0-config>
  3. <!-- 自定义的配置命名-->
  4. <named-config name="c3p0 XML config">
  5.  
  6. <!-- 四个基本信息 -->
  7. <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
  8. <!-- 默认本地可以省略 jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai -->
  9. <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=Asia/Shanghai</property>
  10. <property name="user">root</property>
  11. <property name="password">123456</property>
  12.  
  13. <!-- 连接池管理信息 -->
  14.  
  15. <!-- 连接对象数不够时,每次申请 迭增的连接数 -->
  16. <property name="acquireIncrement">5</property>
  17. <!-- 初始池大小存放的连接对象数 -->
  18. <property name="initialPoolSize">10</property>
  19. <!-- 最小连接对象数 -->
  20. <property name="minPoolSize">10</property>
  21. <!-- 最大连接对象数,不可超出的范围 -->
  22. <property name="maxPoolSize">100</property>
  23. <!-- 最多维护的SQL编译对象个数-->
  24. <property name="maxStatements">50</property>
  25. <!-- 每个连接对象最多可使用的SQL编译对象的个数 -->
  26. <property name="maxStatementsPerConnection">2</property>
  27. </named-config>
  28. </c3p0-config>

注意获取配置名

如果密码错误,其他配置问题,连接池运行一段时间获取不到连接自动超时退出,报异常


封装JdbcForC3P0Util工具类

  1. import java.sql.*;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. /**
  6. * @author ArkD42
  7. * @file Jdbc
  8. * @create 2020 - 04 - 24 - 18:23
  9. */
  10. public class JdbcForC3p0Util {
  11.  
  12. // 池对象只需要一个即可
  13. private static final ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("c3p0 XML config");
  14.  
  15. // 获取连接对象,从池对象获取的对象可允许多个
  16. public static Connection getConnection(){
  17. try {
  18. return comboPooledDataSource.getConnection();
  19. } catch (SQLException sqlException) {
  20. sqlException.printStackTrace();
  21. }
  22. return null;
  23. }
  24.  
  25. // 释放资源 对象没有的情况直接null注入
  26. public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
  27. try{
  28. if (resultSet != null) resultSet.close();
  29. if (preparedStatement != null) preparedStatement.close();
  30. if (connection != null) connection.close();
  31. } catch (SQLException sqlException){
  32. sqlException.printStackTrace();
  33. }
  34. }
  35.  
  36. // 增删改
  37. public static int update(String sql,Object[] args) {
  38. Connection connection = null;
  39. PreparedStatement preparedStatement = null;
  40. try {
  41. connection = getConnection();
  42. preparedStatement = connection.prepareStatement(sql);
  43. if (args != null ) for (int i = 0; i < args.length; i++) preparedStatement.setObject(i+1,args[i]);
  44. int i = preparedStatement.executeUpdate();
  45. return i;
  46. } catch (SQLException e) {
  47. e.printStackTrace();
  48. } finally {
  49. releaseResource(connection,preparedStatement,null);
  50. }
  51. return 0;
  52. }
  53.  
  54. // 查询
  55. public static <T> List<T> queryList(Class<T> tClass, String sql, Object[] args){
  56. Connection connection = null;
  57. PreparedStatement preparedStatement = null;
  58. ResultSet resultSet = null;
  59. try{
  60. connection = getConnection();
  61. preparedStatement = connection.prepareStatement(sql);
  62. if (args != null) for (int i = 0; i < args.length; i++) preparedStatement.setObject(i+1,args[i]);
  63. resultSet = preparedStatement.executeQuery();
  64. ResultSetMetaData metaData = resultSet.getMetaData();
  65. int columnCount = metaData.getColumnCount();
  66. List<T> tList = new ArrayList<T>();
  67. while(resultSet.next()){
  68. T t = tClass.newInstance();
  69. for (int i = 0; i < columnCount; i++) {
  70. Object columnValue = resultSet.getObject(i + 1);
  71. String columnLabel = metaData.getColumnLabel(i + 1);
  72. Field field = tClass.getDeclaredField(columnLabel);
  73. field.setAccessible( true );
  74. field.set(t,columnValue);
  75. }
  76. tList.add(t);
  77. }
  78. return tList;
  79. } catch (Exception e){
  80. e.printStackTrace();
  81. } finally {
  82. releaseResource(connection,preparedStatement,resultSet);
  83. }
  84. return null;
  85. }
  86. }

测试,Blob不可封装为实体类对象,所以大文件的字段我删除了


DBCP 连接池操作

Maven依赖

  1. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
  2. <dependency>
  3.   <groupId>org.apache.commons</groupId>
  4.   <artifactId>commons-dbcp2</artifactId>
  5.   <version>2.7.0</version>
  6. </dependency>
  7.  
  8. <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
  9. <dependency>
  10.   <groupId>org.apache.commons</groupId>
  11.   <artifactId>commons-pool2</artifactId>
  12.   <version>2.8.0</version>
  13. </dependency>

连接实现一,硬编码连接

  1. public class DBCP {
  2.  
  3. @Test
  4. public void dbcp() throws Exception{
  5. // 创建连接池
  6. BasicDataSource dataSource = new BasicDataSource();
  7.  
  8. // 配置信息
  9. dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  10. dataSource.setUrl("jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai");
  11. dataSource.setUsername("root");
  12. dataSource.setPassword("123456");
  13.  
  14. // 连接池管理设置
  15. //dataSource.setInitialSize(10); // 初始化池种的连接对象个数
  16. //dataSource.setMaxIdle(10); // 最大空闲连接对象个数
  17. //dataSource.setMinIdle(2); // 最小空闲连接对象个数
  18.  
  19. // 获取连接对象
  20. Connection connection = dataSource.getConnection();
  21.  
  22. System.out.println(connection);
  23. connection.close();
  24. }
  25. }

测试结果


连接实现二,读取配置文件

dbcp.properties配置文件的信息

  1. # 注意这个driverClassName
  2. driverClassName = com.mysql.cj.jdbc.Driver
  3. url = jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai
  4. # 注意这个username
  5. username = root
  6. password = 123456

测试单元

  1. @Test
  2. public void dbcp2() throws Exception{
  3. InputStream inputStream = DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
  4. Properties properties = new Properties();
  5. properties.load(inputStream);
  6. BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
  7. Connection connection = dataSource.getConnection();
  8. System.out.println(connection);
  9. connection.close();
  10. }

第一种获取方式【通用】

  1. InputStream inputStream = DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");

第二种获取方式

  1. // Maven工程的读取路径
  2. InputStream inputStream = new FileInputStream(new File("src/main/resources/dbcp.properties"));
  3.  
  4. // 普通工程的读取路径
  5. InputStream inputStream = new FileInputStream(new File("src/dbcp.properties"));

第三种获取方式【通用,防空格中文编码不读取】

  1. String file = DBCP.class.getClassLoader().getResource("dbcp.properties").getFile();
  2. String decode = URLDecoder.decode(file, "utf-8");
  3.  
  4. //System.out.println(file);
  5. //System.out.println(decode);
  6.  
  7. InputStream inputStream = new FileInputStream(decode);

测试结果

JdbcDbcpUtil 工具类封装

  1. public class JdbcDbcpUtil {
  2.  
  3. private static DataSource dataSource = null;
  4.  
  5. static {
  6. String path = JdbcDbcpUtil.class.getClassLoader().getResource("dbcp.properties").getFile();
  7. System.out.println(path);
  8. try {
  9. String decode = URLDecoder.decode(path, "utf-8");
  10. InputStream inputStream = new FileInputStream(decode);
  11. Properties properties = new Properties();
  12. properties.load(inputStream);
  13. dataSource = BasicDataSourceFactory.createDataSource(properties);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18.  
  19. public static Connection getConnection(){
  20. try {
  21. return dataSource.getConnection();
  22. } catch (SQLException sqlException) {
  23. sqlException.printStackTrace();
  24. }
  25. return null;
  26. }
  27.  
  28. }

测试结果


Druid连接池实现

Maven依赖

  1. <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
  2. <dependency>
  3. <groupId>com.alibaba</groupId>
  4. <artifactId>druid</artifactId>
  5. <version>1.1.22</version>
  6. </dependency>

硬编码连接

  1. @Test
  2. public void dt1() throws SQLException {
  3. DruidDataSource dataSource = new DruidDataSource();
  4.  
  5. dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  6. dataSource.setUrl("jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai");
  7. dataSource.setUsername("root");
  8. dataSource.setPassword("123456");
  9.  
  10. DruidPooledConnection connection = dataSource.getConnection();
  11. System.out.println(connection);
  12. connection.close();
  13. }

读取配置文件,读取方式跟DBCP几乎一样,配置文件都不需要改

  1. @Test
  2. public void dt2() throws Exception {
  3. String path = DruidTest.class.getClassLoader().getResource("dbcp.properties").getFile();
  4. String decode = URLDecoder.decode(path, "utf-8");
  5. FileInputStream inputStream = new FileInputStream(decode);
  6. Properties properties = new Properties();
  7. properties.load(inputStream);
  8. DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
  9. Connection connection = dataSource.getConnection();
  10. System.out.println(connection);
  11. connection.close();
  12. }

JdbcDruidUtils 工具类封装

【对着DBCP的直接改连接池工厂就完事了】

  1. public class JdbcDruidUtil {
  2.  
  3. private static DataSource dataSource = null;
  4.  
  5. static {
  6. String path = JdbcDbcpUtil.class.getClassLoader().getResource("druid.properties").getFile();
  7. System.out.println(path);
  8. try {
  9. String decode = URLDecoder.decode(path, "utf-8");
  10. InputStream inputStream = new FileInputStream(decode);
  11. Properties properties = new Properties();
  12. properties.load(inputStream);
  13. dataSource = DruidDataSourceFactory.createDataSource(properties);
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. }
  18.  
  19. public static Connection getConnection(){
  20. try {
  21. return dataSource.getConnection();
  22. } catch (SQLException sqlException) {
  23. sqlException.printStackTrace();
  24. }
  25. return null;
  26. }
  27. }

【Java】JDBC Part5 DataSource 连接池操作的更多相关文章

  1. Java java jdbc thin远程连接并操作Oracle数据库

    JAVA jdbc thin远程连接并操作Oracle数据库 by:授客 QQ:1033553122 测试环境 数据库:linux 下Oracle_11g_R2 编码工具:Eclipse 编码平台:W ...

  2. eclipse下jdbc数据源与连接池的配置及功能简介

    今天在做四则运算网页版的时候遇到了一个困惑,由于需要把每个产生的式子存进 数据库,所以就需要很多次重复的加载驱动,建立连接等操作,这样一方面写程序不方便,加大了程序量,另一方面,还有导致数据库的性能急 ...

  3. CP30 ---DataSource连接池的创建过程

    1.参看CP30文档quickStart 如下具体创建步骤 public DataSource getDs() throws Exception { //创建连接池对象 ComboPooledData ...

  4. Java自己动手写连接池四

    Java自己动手写连接池四 测试: package com.kama.cn; import java.sql.Connection; public class Test { public static ...

  5. Java自己动手写连接池三

    Java自己动手写连接池三,核心代码; package com.kama.cn; import java.sql.Connection;import java.util.ArrayList;impor ...

  6. Java 使用 DBCP mysql 连接池 做数据库操作

    需要的jar包有 commons-dbutils , commons-dbcp , commons-pool , mysql-connector-java 本地database.propertties ...

  7. jdbc事务处理和连接池

    JDBC: * JDBC概念:Java DataBase Connectivity(Java数据库连接) SUN公司提供的一组连接数据库API. * JDBC开发步骤: * 1.注册驱动. * 2.获 ...

  8. jdbc基础 (五) 连接池与数据源 DBCP以及C3P0的使用

    一.连接池的概念和使用 在实际应用开发中,特别是在WEB应用系统中,如果JSP.Servlet或EJB使用JDBC直接访问数据库中的数据,每一次数据访问请求都必须经历建立数据库连接.打开数据库.存取数 ...

  9. JAVA中事物以及连接池

    一.事物 什么是事物? 事务,一般是指要做的或所做的事情.在计算机术语中是指访问并可能更新数据库中各种数据项的一个程序执行单元.这些单元要么全都成功,要么全都不成功. 做一件事情,这个一件事情中有多个 ...

  10. Spring整合JDBC和Druid连接池

    我的博客名为黑客之谜,喜欢我的,或者喜欢未来的大神,点一波关注吧!顺便说一下,双十二快到了,祝大家双十二快乐,尽情的买买买~ 如果转载我的文章请标明出处和著名,谢谢配合. 我的博客地址为: https ...

随机推荐

  1. vue局部注册

    只能在当前注册它的vue实例中使用,通过某个 Vue 实例/组件的实例选项 components 注册仅在其作用域中可用的组件 var Child = { template: '<div> ...

  2. HTML 使用动态脚本

    这个 HTML 图片框架 这个HTML支持的脚本属于动态的插件形式的程序 用分段数方式实现动画 1定时器 2函数 计算机有四则运算加减乘除 还有一个是 ^ (shift + 6这个符号是余数,8^3是 ...

  3. 华擎B365M ITX ,SSD WIN7 电脑卡顿,4K异常,9代 I7

    华擎B365M ITX ,SSD WIN7 电脑卡顿,4K异常,9代 I7 故障现象: 新装的电脑,WIN7 电脑卡顿. 表现:我的电脑打开很慢,延时个1-3秒左右.任务管理器打开很慢,N秒. 换了块 ...

  4. Mysql中innodb的B+tree能存储多少数据?

    引言 InnoDB一棵3层B+树可以存放多少行数据?这个问题的简单回答是:约2千万.为什么是这么多呢?因为这是可以算出来的,要搞清楚这个问题,我们先从InnoDB索引数据结构.数据组织方式说起. 在计 ...

  5. PI规划会,研发团队价值聚焦的一剂良方

    随着数字化建设如火如荼地推进,中大型企业的数字化建设团队规模也越来越大,团队规模的扩大一方面带来了更多产能与可能性,另一方面,不同的角色在不同的业务场景也带来了一些现实问题,例如: 作为CIO 或产品 ...

  6. elasticSearch RangeQuery范围查询from to的理解

    elasticSearch RangeQuery范围查询from to的理解 Elasticsearch Guide 选择版本号来查询对应的文档内容:https://www.elastic.co/gu ...

  7. Excel Wps 透视表去重计数方法

    Excel Wps 透视表去重计数方法 在处理表格,遇到处理根据某个列去重后统计数量,而不是仅仅统计数量.在网上查找资料,不确定EXCEL或者WPS某个版本可以支持该功能的实现. 折中的方案,分两步来 ...

  8. Nivdia向量数据库图检索最新标杆——CAGRA

    本文连接:https://wanger-sjtu.github.io/CARGA/ CAGRA 是 N社在RAFT项目中 最新的 ANN 向量索引.这是一种高性能的. GPU 加速的.基于图的方法,尤 ...

  9. FreeRTOS简单内核实现5 阻塞延时

    0.思考与回答 0.1.思考一 为什么 FreeRTOS简单内核实现3 任务管理 文章中实现的 RTOS 内核不能看起来并行运行呢? Task1 延时 100ms 之后执行 taskYIELD() 切 ...

  10. Ansible的常用模块

    目录 ansible常用模块 1. file模块 1.1 file模块的选项 1.2 file模块的使用 1.2.1 使用file模块在远程主机创建文件 1.2.2 创建目录 1.2.3 删除文件/目 ...