1. package com.kuang.lesson04;
    2. import com.kuang.lesson02.utils.JdbcUtils;
    3. import java.sql.*;
    4. public class TestTransaction {
    5. public static void main(String[] args) throws SQLException {
    6. Connection conn =null;
    7. PreparedStatement st= null;
    8. ResultSet rs=null;
    9. try {
    10. conn= JdbcUtils.getConnection();
    11. //关闭数据库的自动提交,自动开启事务
    12. conn.setAutoCommit(false);//开启事务
    13. String sql1 ="update account set money = money-100 where name = 'A'";
    14. st=conn.prepareStatement(sql1);
    15. st.executeUpdate();
    16. String sql2 ="update account set money = money+100 where name = 'B'";
    17. st=conn.prepareStatement(sql2);
    18. st.executeUpdate();
    19. //业务完毕,提交事务
    20. conn.commit();
    21. System.out.println("成功");
    22. } catch (SQLException e) {
    23. try {
    24. conn.rollback();//如果失败就回滚事务
    25. } catch (SQLException ex) {
    26. ex.printStackTrace();
    27. }
    28. e.printStackTrace();
    29. }finally {
    30. JdbcUtils.release(conn,st,rs);
    31. }
    32. }
    33. }