事务开启、关闭、回滚

import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class test {
    @Test
    public void test() throws SQLException {
        String url = "jdbc:mysql://localhost:3306/jdbc";
        String name = "root";
        String pwd = "123456";
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(url,name,pwd);
            connection.setAutoCommit(false);            //事务开启

            String sql01 = "update users set money=money-100 where id=1;";
            preparedStatement = connection.prepareStatement(sql01);
            preparedStatement.executeUpdate();
            String sql02 = "update users set money=money+100 where id=2;";
            preparedStatement.executeUpdate(sql02);
            //System.out.println(1/0);                  //发生异常时会进行事务的回滚
            
            connection.setAutoCommit(true);             //事务关闭
        } catch (Exception e) {
            try {
                connection.rollback();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            preparedStatement.close();		//关闭预处理
            connection.close();				//关闭链接
        }

    }
}

上一篇:[极客大挑战 2019]BuyFlag


下一篇:Hugo博客添加Twikoo评论