MySQL -> JDBC操作事务
ACID
- 代码实现
1.开启事务
2.一组业务执行完毕,提交事务
3.可以在catch语句中显示定义回滚rollback语句,但默认失败就会回滚
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43import com.anobabe.lesson02.utils.JdbcUtils; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class TestTransaction2 { public static void main(String[] args) { Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); //关闭数据库的自动提交,自动会开启事务 conn.setAutoCommit(false); String sql1 = "update account set money = money -100 where name = 'A'"; st = conn.prepareStatement(sql1); st.executeUpdate(); //int x = 1/0; //报错 String sql2 = "update account set money = money +100 where name = 'B'"; st = conn.prepareStatement(sql2); st.executeUpdate(); //业务完毕,提交事务 conn.commit(); System.out.println("成功!"); } catch (SQLException throwables) { //如果失败则默认回滚 // try{ // conn.rollback(); // } catch (SQLException e) { // e.printStackTrace(); // } throwables.printStackTrace(); } finally { JdbcUtils.release(conn,st,rs); } } }
最后
以上就是粗暴流沙最近收集整理的关于17-MySQL-JDBC操作事务的全部内容,更多相关17-MySQL-JDBC操作事务内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复