Java初学笔记41-【自己封装JDBCUtils类、事务、批处理】

七、自己封装JDBCUtils类

1. 介绍

在jdbc操作中,获取连接和释放资源是经常使用到,可以将其封装JDBC连接的工具类JDBCUtils

2. 功能

关闭连接, 得到连接

3.代码实现

package demo;

import javax.xml.transform.Result;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

/**
 * @Package: demo
 * @ClassName: JDBCUtils
 * @Author: 爱吃凉拌辣芒果
 * @CreateTime: 2022/1/7 10:42
 * @Description: 自定义JDBC工具类 JDBCUtils
 * 实现连接与关闭的功能
 */
public class JDBCUtils {
    /**
     * 定义相关的静态属性(4 个), 因为只需要一份,因此,我们做出 static
     */
    private static String url; //数据库信息
    private static String password;  //密码
    private static String user;  //用户名
    private static String driver; //驱动名

    /**
     * 在 static 代码块去初始化相关的静态属性(4 个),
     */
    static {
        try {
            //1. 加载配置文件
            Properties properties = new Properties();
            properties.load(new FileInputStream("src//mysql.properties"));
            //2. 读取相关信息对属性进行赋值
            url = properties.getProperty("url");
            password = properties.getProperty("password");
            user = properties.getProperty("user");
            driver = properties.getProperty("driver");
        } catch (IOException e) {
            //在实际开发中,我们可以这样处理
            //1. 将 编译异常 转成 运行异常
            //2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便.
            throw new RuntimeException(e);
        }
    }

    /**
     * 连接数据库, 返回 Connection
     */
    public static Connection getConnection(){
        try {
            Class<?> aClass = Class.forName(driver);
            Driver driver1 = (Driver) aClass.newInstance();
            DriverManager.registerDriver(driver1);
            Connection connection = DriverManager.getConnection(url,user,password);
            System.out.println("获取连接成功~");
            return connection;
        } catch (Exception e) {
            //在实际开发中,我们可以这样处理
            //1. 将 编译异常 转成 运行异常
            //2. 调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便.
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭相关资源
     */
    public static void close(ResultSet resultSet,Statement statement,Connection connection){
        try {
            if(resultSet != null){
                resultSet.close();
            }
            //这里使用statement是因为它是preparedStatement的父类
            if(statement != null){
                statement.close();
            }
            if(connection != null){
                connection.close();
            }
            System.out.println("已断开连接~");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

4. 使用演示

1. DML

/**
     * 使用 JDBCUtils 工具类演示 增删改
     */
    @Test
    public void TestDML(){
        //1. 得到连接,连接数据库demo
        Connection connection = null;

        //2. 组织sql语句
        String sql1 = "update man set name = ? where id = ?";
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.setString(1,"梅花");
            preparedStatement.setInt(2,3);
            //执行
            preparedStatement.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //关闭资源
            JDBCUtils.close(null,preparedStatement,connection);
        }

    }

2. select

/**
     * 使用 JDBCUtils 工具类演示 查询
     */
    @Test
    public void TestSelect(){
        //1. 换取连接
        Connection connection = null;

        //2.组织sql语句
        String sql1 = "select * from man";
        ResultSet resultSet = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql1);
            resultSet = preparedStatement.executeQuery(sql1);
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                System.out.println(id + " " + name);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JDBCUtils.close(resultSet,preparedStatement,connection);
        }

    }

八、事务

1. 基本介绍

(1)JDBC程序中当一个Connection对象创建时,默认情况下是自动提交事务:每次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
(2)JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
(3)调用Connection的setAutoCommit(false)可以取消自动提交事务
(4)在所有的SQL语句都成功执行后,调用Connection 的commit()方法提交事务
(5)在其中某个操作失败或出现异常时,调用Connection的rollback();方法回滚事务

2. 模拟经典的转账业务

(1)不使用事务

在这里插入图片描述

在这里插入图片描述

package demo.transaction;

import demo.JDBCUtils;
import org.junit.jupiter.api.Test;

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

/**
 * @Package: demo.transaction
 * @ClassName: NoTransaction
 * @Author: 爱吃凉拌辣芒果
 * @CreateTime: 2022/1/19 14:14
 * @Description: 不使用事务模拟经典的转账业务
 */
public class NoTransaction {
    @Test
    public void noTransactrion(){
        //1. 得到连接
        Connection connection = null;

        //2. 发送命令
        String sql1 = "UPDATE `account` SET balance = balance - 100 WHERE `name` = '马云';";
        String sql2 = "UPDATE `account` SET balance = balance + 100 WHERE `name` = '马化腾';";

        PreparedStatement preparedStatement = null;
        try {
            // 在默认情况下,connection 是默认自动提
            connection = JDBCUtils.getConnection();
            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            int a = 1 / 0;  // 会抛出异常
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            //3. 关闭连接
            JDBCUtils.close(null,preparedStatement,connection);
        }
    }
}

(2)使用事务

在这里插入图片描述

在这里插入图片描述

package demo.transaction;

import demo.JDBCUtils;
import org.junit.jupiter.api.Test;

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

/**
 * @Package: demo.transaction
 * @ClassName: UseTransaction
 * @Author: 爱吃凉拌辣芒果
 * @CreateTime: 2022/1/19 14:53
 * @Description:
 */
public class UseTransaction {
    @Test
    public void useTransactrion(){
        //1. 得到连接
        Connection connection = null;

        //2. 发送命令
        String sql1 = "UPDATE `account` SET balance = balance - 100 WHERE `name` = '马云';";
        String sql2 = "UPDATE `account` SET balance = balance + 100 WHERE `name` = '马化腾';";

        PreparedStatement preparedStatement = null;
        try {
            // 在默认情况下,connection 是默认自动提
            connection = JDBCUtils.getConnection();

            //将 connection 设置为不自动提
            connection.setAutoCommit(false);

            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            //int a = 1 / 0;  // 会抛出异常
            preparedStatement = connection.prepareStatement(sql2);
            preparedStatement.executeUpdate();

            //提交事务
            connection.commit();

        } catch (SQLException throwables) {
            System.out.println("出现了异常");
            try {
                connection.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        } finally {
            //3. 关闭连接
            JDBCUtils.close(null,preparedStatement,connection);
        }
    }
}

九、批处理

1. 基本介绍

(1)当需要成批插入或者更新记录时。可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。
(2)JDBC的批量处理语句包括下面方法:
【1】addBatch():添加需要批量处理的SQL语句或参数
【2】executeBatch():执行批量处理语句;
【3】clearBatch():清空批处理包的语句
(3)JDBC连接MySQL时,如果要使用批处理功能,在url中加参数?
rewriteBatchedStatements=true
(4)批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高

2. 应用实例

package demo.batch;

import demo.JDBCUtils;
import org.junit.jupiter.api.Test;

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

/**
 * @Package: demo.batch
 * @ClassName: UseBatch
 * @Author: 爱吃凉拌辣芒果
 * @CreateTime: 2022/1/25 12:05
 * @Description: 批处理与一般情况的对比
 */
public class UseBatch {
    @Test
    public void normal() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into test_batch values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setInt(1,i);
            preparedStatement.setString(2,"大志"+i);
            preparedStatement.executeUpdate();
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));  //耗时:150501
        JDBCUtils.close(null,preparedStatement,connection);
    }

    @Test
    public void useBatch() throws Exception {
        Connection connection = JDBCUtils.getConnection();
        String sql = "insert into test_batch values(?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 5000; i++) {
            preparedStatement.setInt(1,i);
            preparedStatement.setString(2,"大志"+i);
            preparedStatement.addBatch();
            if((i + 1) % 1000 == 0){
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时:" + (end - start));  //耗时:783
        JDBCUtils.close(null,preparedStatement,connection);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱吃凉拌辣芒果

不断学习,不断进步,共勉~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值