通过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);
}
}
执行前:
执行后:
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);
}
}
执行提示异常:
数据没有改变:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架