批处理和数据库连接池
  TEZNKK3IfmPf 2023年11月13日 37 0

1.1 基本介绍

1. 当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。

2. JDBC的批量处理语句包括 下面方法:

addBatch():添加需要批量处理的SQL语句或参数

executeBatch():执行批量处理语句;

clearBatch():清空批处理包的语句

3. JDBC连接MySQL时, 如果要使用批处理功能,请再url中加

参数?rewriteBatchedStatements= true

4.批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高

1.2 应用实例   838

1.演示向admin2表中添加5000条数据,看看使用批处理耗时多久

2.注意:需要修改配置文件jdbc.properties

url =jdbc:mysql://localhost:3306/数据库?rewriteBatchedStatements=true

批处理和数据库连接池

 

批处理和数据库连接池

代码在com.stulzl.batch_.

Batch_
package com.stulzl.batch_;


import com.stulzl.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

//演示Java的批处理
public class Batch_ {

    //传统方法,添加5000条数据到admin2
    @Test
    public void noBatch() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();//开始时间
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1,"jack"+i);
            preparedStatement.setString(2,"666");
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();//结束时间

        System.out.println("传统方式="+(end-start));//传统方式=4654
        //关闭连接
        JDBCUtils.close(null,preparedStatement,connection);
    }

    //使用批量添加方式
    @Test
    public void Batch() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into admin2 values(null,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("开始执行");
        long start = System.currentTimeMillis();//开始时间
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setString(1,"jack"+i);
            preparedStatement.setString(2,"666");
            //将sql语句加入到批处理包中
            preparedStatement.addBatch();
            //当有1000记录时,再批量处理
            if((i+1)%1000==0){//满1000条sql语句
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();//清空一把
            }
        }
        long end = System.currentTimeMillis();//结束时间

        System.out.println("批量方式="+(end-start));//批量方式=76
        //关闭连接
        JDBCUtils.close(null,preparedStatement,connection);
    }
}
代码在E:\java学习\初级\course171\db_
batch_
-- 批量处理  838
CREATE TABLE admin2
	(id INT PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(32) NOT NULL,
	PASSWORD VARCHAR(32) NOT NULL);
SELECT * FROM admin2 
DROP TABLE admin2

2. 数据库连接池  840

2.1   传统方法 5k 次连接数据库问题

1. 编写程序完成连接MySQL 5000次的操作

2. 看看有什么问题,耗时又是多久. =>数据库连接池

代码在com.stulzl.datasource_

ConQuestion
package com.stulzl.datasource_;

import com.stulzl.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.Connection;

//连接池问题引入   840
public class ConQuestion {
    //代码连接数据库5000次
    @Test
    //看看连接-关闭 connection 会耗用多
    public void testCon(){
        long start = System.currentTimeMillis();
        System.out.println("开始连接.....");
        for (int i=0;i<5000;i++) {
            //使用传统的 jdbc 方式,得到连接
            Connection connection = JDBCUtils.getConnection();
            //做一些工作,比如得到 PreparedStatement ,发送 sql
            //..........
            // 关闭
            JDBCUtils.close(null, null, connection);
        }
        long end = System.currentTimeMillis();
        System.out.println("传统方式 5000 次 耗时=" + (end - start));//传统方式 5000 次 耗时=9620
    }
}

2.2 传统获取 Connection 问题分析  840

1. 传统的JDBC数据库连接使用DriverManager来获取,每次向数据库建立连接的时候都要将Connection加载到内存中,再验证IP地址,用户名和密码(0.05s ~ 1s时间)。需要数据库连接的时候,就向数据库要求一个,频繁的进行数据库连接操作将占用很多的系统资源,容易造成服务器崩溃。

2.每一次数据库连接,使用完后都得断开,如果程序出现异常而未能关闭,将导致数据库内存泄漏,最终将导致重启数据库。

3. 传统获取连接的方式,不能控制创建的连接数量,如连接过多,也可能导致内存泄漏,MySQL崩溃。

4.解决传统开发中的数据库连接问题,可以采用数据库连接池技术(connection pool)。

2.3 数据库连接池基本介绍   841

1. 预先在缓冲池中放入定数量的连接,当需要建立数据库连接时,只需从“缓冲池"中取出一个,使用完毕之后再放回去。

2.数据库连接池负责分配、 管理和释放数据库连接,它允许应用程序重复使用个现有的数据库连接,而不是重新建立一个。

3.当应用程序向连接池请求的连接数超过最大连接数量时,这些请求将被加入到等待队列中

批处理和数据库连接池

批处理和数据库连接池

2.4 数据库连接池种类   841

1. JDBC的数据库连接池使用javax.sql.DataSource来表示,DataSource只是一个接口,该接口通常由第三方提供实现[提供jar]

2.C3P0数据库连接池,速度相对较慢,稳定性不错(hibernate, spring)

3.DBCP数据库连接池,速度相对c3p0较快,但不稳定

4.Proxool数据库连接池,有监控连接池状态的功能,稳定性较c3p0差一点BoneCP数据库连接池,速度快

6.Druid(德鲁伊)是阿里提供的数据库连接池,集DBCP、C3P0、 Proxool优点于一身的数据库连接池

2.5 C3P0 应用实例 5000次连接数据库  842-843

使用代码实现c3p0数据库连接池,配置文件放src目录C3P0 java

代码在com.stulzl.c3p0_

C3P0_
package com.stulzl.c3p0_;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

//演示c3p0的使用   842-843
public class C3P0_ {
//先放入jar包
    //方式 1: 相关参数,在程序中指定 user, url , password 等
    @Test
    public void testC3P0_01() throws Exception {
        //1.创建一个数据源对象
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        //2. 通过配置文件获取相关的信息
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\mysql.properties"));
        //读取相关的属性数据
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        //给数据源comboPooledDataSource 设置相关的参数
        //注意:连接管理是由 comboPooledDataSource 来管理
        comboPooledDataSource.setDriverClass(driver);
        comboPooledDataSource.setJdbcUrl(url);
        comboPooledDataSource.setUser(user);
        comboPooledDataSource.setPassword(password);

        //设置初始化连接数
        comboPooledDataSource.setInitialPoolSize(10);
        //设置最大连接数
        comboPooledDataSource.setMaxPoolSize(50);
        //测试连接池的效率, 测试对 mysql 5000 次操作
        long start = System.currentTimeMillis();
        for(int i=0;i<5000;i++){
            //这个方法就是从 DataSource 接口实现的
            Connection connection = comboPooledDataSource.getConnection();
            //System.out.println("连接成功");
            //关闭
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0 5000次连接耗时="+(end-start));//c3p0 5000次连接耗时=336
    }

    //方式二使用配置文件模板来完成   843
    //1. 将 c3p0 提供的 c3p0.config.xml 拷贝到 src 目录下
    //2. 该文件指定了连接数据库和连接池的相关参数
    @Test
    public void testC3P0_02() throws SQLException {
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("hsp_edu");
        //测试连接池的效率, 测试对 mysql 5000 次操作
        long start = System.currentTimeMillis();
        for(int i=0;i<500000;i++) {
            Connection connection = comboPooledDataSource.getConnection();
            //System.out.println("连接成功~");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("c3p0 第二种500000次连接耗时="+(end-start));//c3p0 第二种500000次连接耗时=1630
    }
}
配置文件c3p0-config.xml
<c3p0-config>
    <!-- 数据源名称代表连接池 -->
  <named-config name="hsp_edu">
<!-- 驱动类 -->
  <property name="driverClass">com.mysql.jdbc.Driver</property>
  <!-- url-->
  	<property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/hsp_db02</property>
  <!-- 用户名 -->
  		<property name="user">root</property>
  		<!-- 密码 -->
  	<property name="password">lzl</property>
  	<!-- 每次增长的连接数-->
    <property name="acquireIncrement">5</property>
    <!-- 初始的连接数 -->
    <property name="initialPoolSize">10</property>
    <!-- 最小连接数 -->
    <property name="minPoolSize">5</property>
   <!-- 最大连接数 -->
    <property name="maxPoolSize">50</property>

	<!-- 可连接的最多的命令对象数 -->
    <property name="maxStatements">5</property> 
    
    <!-- 每个连接对象可连接的最多的命令对象数 -->
    <property name="maxStatementsPerConnection">2</property>
  </named-config>
</c3p0-config>

3. Druid(德鲁伊)   844

3.1 应用实例  844

使用代码实现Druid(德鲁伊)数据库连接池

代码在com.stulzl.druid_

Druid_

package com.stulzl.druid_;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;

//演示的Druid的使用  844
public class Druid_ {
    @Test
    public void testDruid() throws Exception {
        //1. 加入 Druid jar 包
        //2. 加入 配置文件 druid.properties , 将该文件拷贝项目的 src 目录
        //3. 创建 Properties 对象, 读取配置文件
        Properties properties = new Properties();
        properties.load(new FileInputStream("src\\druid.properties"));

        //4. 创建一个指定参数的数据库连接池,Druid连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 500000; i++) {
            Connection connection = dataSource.getConnection();
            //System.out.println("连接成功!");
            connection.close();
        }
        long end = System.currentTimeMillis();
        System.out.println("druid连接池500000操作耗时="+(end-start));//druid连接池500000操作耗时=410
    }

}

配置文件druid.properties

#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/hsp_db02?rewriteBatchedStatements=true
username=root
password=lzl
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=50
#max wait time (5000 mil seconds)
maxWait=5000

3.2 将 JDBCUtils 工具类改成 Druid(德鲁伊)实现  845

通过德鲁伊数据库连接池获取连接对象

可以简单的演示下使用

代码在com.stulzl.jdbcutils_druid;

JDBCUtils_Druid 

package com.stulzl.jdbcutils_druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

//这是一个基于druid的数据库连接池的工具类  845
//将 JDBCUtils 工具类改成 Druid(德鲁伊)实现
public class JDBCUtils_Druid {
    private static DataSource ds;

    //在静态代码块完成ds的初始化
    static{
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //编写getConnection方法
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
    //关闭连接, 再次强调: 在数据库连接池技术中,close 不是真的断掉连接
    //而是把使用的 Connection 对象放回连接池
    public static void close(ResultSet resultSet, Statement statement, Connection connection){
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

测试类JDBCUtils_Druid_USE

package com.stulzl.jdbcutils_druid;

import com.stulzl.utils.JDBCUtils;
import org.junit.jupiter.api.Test;

import java.sql.*;

//测试基于druid的数据库连接池的工具类  845
public class JDBCUtils_Druid_USE {
    @Test
    public void testSelect(){

        System.out.println("使用druid工具类方式完成");

        //1.得到连接
        Connection connection = null;
        //2.组织一个sql语句
        String sql = "select * from actor where id=?";
        PreparedStatement preparedStatement=null;
        ResultSet set = null;
        try {
            connection = JDBCUtils_Druid.getConnection();
            //3.创建preparedStatement对象
            preparedStatement = connection.prepareStatement(sql);

            //4. 给占位符赋值
            preparedStatement.setInt(1,2);

            //执行,得到结果集
            set = preparedStatement.executeQuery();

            //遍历该结果集
            while(set.next()){
                int id = set.getInt("id");//这里提示("id")可以直接写,也可以写数字(按对应顺序)
                String name = set.getString("name");
                String sex = set.getString("sex");
                Date borndate = set.getDate("borndate");
                String phone = set.getString("phone");
                System.out.println(id + "\t" + name + "\t" + sex
                        + "\t" + borndate + "\t" + phone);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils_Druid.close(set,preparedStatement,connection);
        }
    }
}
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   23天前   50   0   0 java
  TEZNKK3IfmPf   2024年05月31日   31   0   0 数据库mysql
TEZNKK3IfmPf