MySQL入门教程:JDBC事务&API阅读&DAO模式

1、事务及回滚点

JDBC中使用事务

    事务回顾:

     事务概念:在逻辑上一组不可分割的操作,由多个sql语句组成,多个sql语句要么全都执行成功,要么都不执行.  原子性 一致性  隔离性 持久性

     JDBC控制事物主要就是在学习如何让多个数据库操作成为一个整体,实现要么全都执行成功,要么全都不执行

     在JDBC中,事务操作是自动提交。一条对数据库的DML(insert、update、delete)代表一项事务操作,操作成功后,系统将自动调用commit()提交,否则自动调用rollback()回滚,在JDBC中,事务操作方法都位于接口java.sql.Connection中,可以通过调用setAutoCommit(false)来禁止自动提交。之后就可以把多个数据库操作的表达式作为一个事务,在操作完成后调用commit()来进行整体提交,倘若其中一个表达式操作失败,都不会执行到commit(),并且将产生响应的异常;此时就可以在异常捕获时调用rollback()进行回滚,回复至数据初始状态.事务开始的边界则不是那么明显了,它会开始于组成当前事务的所有statement中的第一个被执行的时候。事务结束的边界是commit或者rollback方法的调用

  使用事务保证转账安全性


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

public class TestTransaction {

    private static String driver ="com.mysql.cj.jdbc.Driver";
    private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";
    private static String user="root";
    private static String password="root";
    public static void main(String[] args) {
        testTransaction();
    }
    // 定义一个方法,向部门表增加1000条数据
    public static void testTransaction(){
        Connection connection = null;
        PreparedStatement preparedStatement=null;


        /*
        * JDBC 默认是自动提交事务
        * 每条DML都是默认提交事务的,多个preparedStatement.executeUpdate();都会提交一次事务
        * 如果想手动控制事务,那么就不能让事务自动提交
        * 通过Connection对象控制connection.setAutoCommit(false);
        * 如果不设置 默认值为true,自动提交,设置为false之后就是手动提交了
        * 无论是否发生回滚,事务最终会一定要提交的 提交我们建议放在finally之中进行提交
        * 如果是转账的过程中出现异常了,那么我们就要执行回滚,回滚操作应该方法catch语句块中
        *
        * */
        try{
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user,password);
            // 设置事务手动提交
            connection.setAutoCommit(false);
            String sql="update account set money =money- ? where aid = ?";
            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句
            // 转出
            preparedStatement.setDouble(1, 100);
            preparedStatement.setInt(2, 1);
            preparedStatement.executeUpdate();
            // 产生异常
            //int i =1/0;

            // 转入
            preparedStatement.setDouble(1, -100);
            preparedStatement.setInt(2, 2);
            preparedStatement.executeUpdate();

        }catch (Exception e){
            if(null != connection){
                try {
                    connection.rollback();// 回滚事务
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            // 提交事务
            if(null != connection){
                try {
                    connection.commit();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null != preparedStatement){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null != connection){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

 设置回滚点

import java.sql.*;
import java.util.LinkedList;


public class TestTransaction2 {
    private static String driver ="com.mysql.cj.jdbc.Driver";
    private static String url="jdbc:mysql://127.0.0.1:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&useServerPrepStmts=true&cachePrepStmts=true&&rewriteBatchedStatements=true";
    private static String user="root";
    private static String password="root";
    public static void main(String[] args) {
        testAddBatch();
    }
    // 定义一个方法,向部门表增加1000条数据
    public static void testAddBatch(){
        Connection connection = null;
        PreparedStatement preparedStatement=null;

        LinkedList<Savepoint> savepoints =new LinkedList<Savepoint>();
        try{
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user,password);
            connection.setAutoCommit(false);
            String sql="insert into dept values (DEFAULT ,?,?)";
            preparedStatement = connection.prepareStatement(sql);//这里已经传入SQL语句

            //设置参数
            for (int i = 1; i <= 10663; i++) {
                preparedStatement.setString(1, "name");
                preparedStatement.setString(2, "loc");
                preparedStatement.addBatch();// 将修改放入一个批次中
                if(i%1000==0){
                    preparedStatement.executeBatch();
                   preparedStatement.clearBatch();// 清除批处理中的数据
                    // 设置回滚点
                    Savepoint savepoint = connection.setSavepoint();
                    savepoints.addLast(savepoint);
                }
                // 数据在 100001条插入的时候出现异常
                if(i ==10001){
                    int x =1/0;
                }
            }

            /*
            * 整数数组中的元素代表执行的结果代号
            * SUCCESS_NO_INFO -2
            * EXECUTE_FAILED  -3
            * */
            /*int[] ints = */
            preparedStatement.executeBatch();
            preparedStatement.clearBatch();

        }catch (Exception e){
            if(null != connection){
                try {
                    //Savepoint sp = savepoints.getLast();
                    Savepoint sp = savepoints.get(4);
                    if(null != sp){
                        // 选择回滚点
                        connection.rollback(sp);// 回滚
                    }

                } catch (SQLException e2) {
                    e2.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            if(null != connection){
                try {
                    connection.commit();// 提交
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null != preparedStatement){
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(null != connection){
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2、JDBCAPI总结_阅读

JDBC API总结

Connection接口

•作用:代表数据库连接

 

方法摘要

 

 

 void

 

 

close () 
 
  立即释放此   Connection  对象的数据库和 JDBC 资源,而不是等待它们被自动释放。

 

 

 void

 

 

commit () 
         
   使所有上一次提交/回滚后进行的更改成为持久更改,并释放此 Connection  对象当前持有的所有数据库锁。

 

 

 Statement

 

 

createStatement () 
         
   创建一个   Statement  对象来将 SQL 语句发送到数据库。

 

 

 CallableStatement

 

 

prepareCall (

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

山竹之七语

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值