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依赖

<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>

第一种,硬编码的连接池

package connector;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test; import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException; /**
* @author ArkD42
* @file Jdbc
* @create 2020 - 04 - 24 - 17:49
*/
public class C3P0Test { @Test
public void dataSourceByC3p0() throws PropertyVetoException, SQLException {
// 获取池对象
ComboPooledDataSource dataSource = new ComboPooledDataSource();
// 配置连接信息
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_db?serverTimezone=Asia/Shanghai");
dataSource.setUser("root");
dataSource.setPassword("123456");
//设置初始的连接数
dataSource.setInitialPoolSize(10);
//获取连接
Connection connection = dataSource.getConnection();
System.out.println(connection);
}
}

测试结果

第二种 XML配置文件

配置XML配置文件的信息

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

注意获取配置名

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


封装JdbcForC3P0Util工具类

import java.sql.*;
import java.util.ArrayList;
import java.util.List; /**
* @author ArkD42
* @file Jdbc
* @create 2020 - 04 - 24 - 18:23
*/
public class JdbcForC3p0Util { // 池对象只需要一个即可
private static final ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("c3p0 XML config"); // 获取连接对象,从池对象获取的对象可允许多个
public static Connection getConnection(){
try {
return comboPooledDataSource.getConnection();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return null;
} // 释放资源 对象没有的情况直接null注入
public static void releaseResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
try{
if (resultSet != null) resultSet.close();
if (preparedStatement != null) preparedStatement.close();
if (connection != null) connection.close();
} catch (SQLException sqlException){
sqlException.printStackTrace();
}
} // 增删改
public static int update(String sql,Object[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
if (args != null ) for (int i = 0; i < args.length; i++) preparedStatement.setObject(i+1,args[i]);
int i = preparedStatement.executeUpdate();
return i;
} catch (SQLException e) {
e.printStackTrace();
} finally {
releaseResource(connection,preparedStatement,null);
}
return 0;
} // 查询
public static <T> List<T> queryList(Class<T> tClass, String sql, Object[] args){
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try{
connection = getConnection();
preparedStatement = connection.prepareStatement(sql);
if (args != null) for (int i = 0; i < args.length; i++) preparedStatement.setObject(i+1,args[i]);
resultSet = preparedStatement.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
List<T> tList = new ArrayList<T>();
while(resultSet.next()){
T t = tClass.newInstance();
for (int i = 0; i < columnCount; i++) {
Object columnValue = resultSet.getObject(i + 1);
String columnLabel = metaData.getColumnLabel(i + 1);
Field field = tClass.getDeclaredField(columnLabel);
field.setAccessible( true );
field.set(t,columnValue);
}
tList.add(t);
}
return tList;
} catch (Exception e){
e.printStackTrace();
} finally {
releaseResource(connection,preparedStatement,resultSet);
}
return null;
}
}

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


DBCP 连接池操作

Maven依赖

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-dbcp2</artifactId>
  <version>2.7.0</version>
</dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-pool2</artifactId>
  <version>2.8.0</version>
</dependency>

连接实现一,硬编码连接

public class DBCP {

    @Test
public void dbcp() throws Exception{
// 创建连接池
BasicDataSource dataSource = new BasicDataSource(); // 配置信息
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("123456"); // 连接池管理设置
//dataSource.setInitialSize(10); // 初始化池种的连接对象个数
//dataSource.setMaxIdle(10); // 最大空闲连接对象个数
//dataSource.setMinIdle(2); // 最小空闲连接对象个数 // 获取连接对象
Connection connection = dataSource.getConnection(); System.out.println(connection);
connection.close();
}
}

测试结果


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

dbcp.properties配置文件的信息

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

测试单元

    @Test
public void dbcp2() throws Exception{
InputStream inputStream = DBCP.class.getClassLoader().getResourceAsStream("dbcp.properties");
Properties properties = new Properties();
properties.load(inputStream);
BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

第一种获取方式【通用】

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

第二种获取方式

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

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

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

测试结果

JdbcDbcpUtil 工具类封装

public class JdbcDbcpUtil {

    private static DataSource dataSource = null;

    static {
String path = JdbcDbcpUtil.class.getClassLoader().getResource("dbcp.properties").getFile();
System.out.println(path);
try {
String decode = URLDecoder.decode(path, "utf-8");
InputStream inputStream = new FileInputStream(decode);
Properties properties = new Properties();
properties.load(inputStream);
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
} public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return null;
} }

测试结果


Druid连接池实现

Maven依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>

硬编码连接

    @Test
public void dt1() throws SQLException {
DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///jdbc_db?serverTimezone=Asia/Shanghai");
dataSource.setUsername("root");
dataSource.setPassword("123456"); DruidPooledConnection connection = dataSource.getConnection();
System.out.println(connection);
connection.close();
}

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

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

JdbcDruidUtils 工具类封装

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

public class JdbcDruidUtil {

    private static DataSource dataSource = null;

    static {
String path = JdbcDbcpUtil.class.getClassLoader().getResource("druid.properties").getFile();
System.out.println(path);
try {
String decode = URLDecoder.decode(path, "utf-8");
InputStream inputStream = new FileInputStream(decode);
Properties properties = new Properties();
properties.load(inputStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
} public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return null;
}
}

【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. scala怎么退出

    scala怎么退出 scala> :help //查看帮助 All commands can be abbreviated, e.g., :he instead of :help. :edit ...

  2. work05

    第一题:分析以下需求,并用代码实现 手机类Phone 属性: 品牌brand 价格price 行为: 打电话call() 发短信sendMessage() 玩游戏playGame() 要求: 1.按照 ...

  3. 比较 SpringSecurity 和 Shiro

    相比 Spring Security, Shiro 在保持强大功能的同时,使用简单性和灵活性. SpringSecurity: 即使是一个一个简单的请求, 最少得经过它的 8 个Filter.Spri ...

  4. 用CSS3绘制iPhone手机

    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` 用CSS3绘制iPhone手机 日期:2017-7-3 阿 ...

  5. python中dict和list的数据结构

    要理解dict的有关内容需要你理解哈希表(map)的相关基础知识,这个其实是<算法与数据结构>里面的内容. 1.list和tuple其实是用链表顺序存储的,也就是前一个元素中存储了下一个元 ...

  6. NXP i.MX 8M Plus工业开发板规格书(四核ARM Cortex-A53 + 单核ARM Cortex-M7,主频1.6GHz)

      1 评估板简介 创龙科技TLIMX8MP-EVM是一款基于NXP i.MX 8M Plus的四核ARM Cortex-A53 + 单核ARM Cortex-M7异构多核处理器设计的高性能工业评估板 ...

  7. Mac下Eclipse打不开了怎么办

    其实这个问题能搜到很多答案,但是对我有效的只有下面这一种. 背景 我需要使用到Eclipse,就下载了它的特定版本,用于开发RAP的. 连续两次都是使用后关闭,就再也打不开了. 选定的解决方案 试了好 ...

  8. ubuntu16 安装 python-networkmanager 失败

    前言 ubuntu16 安装 python-networkmanager 失败 解决方案 sudo apt-get install libdbus-1-dev sudo apt-get install ...

  9. 做一个单纯的react-image显示组件

    最近项目上有一个需求,在显示图片的时候,需要传递自定义的头部就行认证.google了一番之后,发现没有现成的组件库可以使用[也可能是我没找到],所以请求图片只能采用xhr方式来异步加载.下面就是在做这 ...

  10. Vite5+Electron聊天室|electron31跨平台仿微信EXE客户端|vue3聊天程序

    基于electron31+vite5+pinia2跨端仿微信Exe聊天应用ViteElectronChat. electron31-vite5-chat原创研发vite5+electron31+pin ...