通过JDBC操作事务示例

1. 简单的事务操作示例

import utils.JdbcUtils;

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

public class TestTransaction {
    private static Connection connect = null;

    private static PreparedStatement preparedStatement = null;


    public static void main(String[] args) throws Exception {
        connect = JdbcUtils.getConnect();

        // 关闭自动提交
        connect.setAutoCommit(false);

        String sql = "update workdb.t_students set score = score - 10 where name = '小明'";
        preparedStatement = connect.prepareStatement(sql);
        preparedStatement.executeUpdate();

        String sql2 = "update workdb.t_students set score = score + 10 where name = '小美'";
        preparedStatement = connect.prepareStatement(sql2);
        preparedStatement.executeUpdate();

		// 提交事务
        connect.commit();
        System.out.println("commit successful!");

		// 关闭连接
        JdbcUtils.releaseConnection(connect, preparedStatement, null);
    }
}

执行前:
image

执行后:
image

2.测试事务回滚

import utils.JdbcUtils;

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

/**
 * @author: 乌蝇哥
 * @createDate: 2023/6/28
 * @description:
 */
public class TestTransaction {
    private static Connection connect = null;

    private static PreparedStatement preparedStatement = null;


    public static void main(String[] args) throws Exception {
        connect = JdbcUtils.getConnect();

        // 关闭自动提交
        connect.setAutoCommit(false);

        String sql = "update workdb.t_students set score = score - 10 where name = '小明'";
        preparedStatement = connect.prepareStatement(sql);
        preparedStatement.executeUpdate();
        // 如果这里提交了,则程序异常后,不能rollback回滚
//        connect.commit();

        // 插入异常, 只要没有commit提交事务,程序异常后会自动rollback
        int i = 2 / 0;

        String sql2 = "update workdb.t_students set score = score + 10 where name = '小美'";
        preparedStatement = connect.prepareStatement(sql2);
        preparedStatement.executeUpdate();

        // 提交事务
        connect.commit();
        System.out.println("commit successful!");

        // 关闭连接
        JdbcUtils.releaseConnection(connect, preparedStatement, null);
    }
}

执行提示异常:
image

数据没有改变:
image

posted @   遥遥领先  阅读(26)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
点击右上角即可分享
微信分享提示