package com.lc.test01;


import java.sql.*;

public class Test04_tx {

    public static void main(String[] args) throws Exception {
        //张三给李四转账 100

        boolean flag = trasnfer(1,2,100);

        if (flag){
            System.out.println("执行成功");
        }else {
            System.out.println("执行失败");
        }

    }

    public static boolean trasnfer(int zsId,int lsId,int money) throws Exception{
        //获取连接
        String url = "jdbc:mysql:///db2";
        String user = "root";
        String pass = "123456";
        Connection connection = DriverManager.getConnection(url, user, pass);

        //开启事务
        connection.setAutoCommit(false);

        String sql1 = " UPDATE `t_user` SET `money` = `money` - ? WHERE `id` = ? ; ";
        String sql2 = " UPDATE `t_user` SET `money` = `money` + ? WHERE `id` = ? ; ";

        //sql执行对象
        PreparedStatement p1 = connection.prepareStatement(sql1);
        p1.setInt(1,money);
        p1.setInt(2,zsId);

        PreparedStatement p2 = connection.prepareStatement(sql2);
        p2.setInt(1,money);
        p2.setInt(2,lsId);

        try {
            //执行sql
            p1.executeUpdate();
            int a = 10/0;
            p2.executeUpdate();

            //提交事务
            connection.commit();

            return true;
        } catch (SQLException e) {
            //ctrl + alt + t 生成try catch
            //回滚
            connection.rollback();
            e.printStackTrace();
            return false;
        }finally {
            //释放
            p2.close();
            p1.close();
            connection.close();
        }
    }
}
