栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

Java初学笔记41

七、自己封装JDBCUtils类

1. 介绍2. 功能3.代码实现4. 使用演示

1. DML2. select 八、事务

1. 基本介绍2. 模拟经典的转账业务

(1)不使用事务(2)使用事务 九、批处理

1. 基本介绍2. 应用实例

七、自己封装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;


public class JDBCUtils {
    
    private static String url; //数据库信息
    private static String password;  //密码
    private static String user;  //用户名
    private static String driver; //驱动名

    
    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);
        }
    }

    
    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
    @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
    @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;


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;


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;


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);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759801.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号