mysql之事务范例

package com.yeyue.lesson04;

import com.yeyue.lesson02.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class TestTransaction1 {
    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 company set money = money - 100 where name = 'A'";
            st = conn.prepareStatement(sql1);
            st.executeUpdate();

            //int x = 1/0; //报错

            String sql2 = "update company 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);
        }
    }
}

 

posted @ 2021-08-31 10:59  深夜暗月  阅读(148)  评论(0)    收藏  举报