一、总体设计
1.开启链接:使用 try{}catch(){}代码块
2.开启事务
3.事务提交
4.事务回滚
mysql属于自动事物提交,只要把自动提交关闭,这些动作就都在一个一个事务中了
try{
//开启事务
//关闭事务提交
connection.setAutoCommit(false);
//执行数据库动作
//执行数据库动作
//事务提交
connection.commit();
}catch(Exception e){
//事务回滚
connection.rollback();
//将异常抛出
throw e;
}
二、代码实现
1.Dao层
package com.transaction;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* DAO层,负责实现数据的增删改查
*/
public class BankDao {
/**
* 加钱方法
* @param account 加钱的账号
* @param money 加钱数
*/
public void add(String account,int money,Connection connection) throws Exception {
String sql = "update t_bank set money = money + ? where account = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,money);
preparedStatement.setObject(2,account);
preparedStatement.executeUpdate();
}
/**
* 减钱方法
* @param account 减钱的账号
* @param money 减钱数x
*/
public void sub(String account,int money,Connection connection) throws Exception {
String sql = "update t_bank set money = money - ? where account = ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1,money);
preparedStatement.setObject(2,account);
preparedStatement.executeUpdate();
}
}
2.Service层
package com.transaction;
import org.junit.Test;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 业务层
*/
public class BankServices {
@Test
public void start() throws Exception{
transfer("ergouzi","lvdandan",500);
}
public void transfer(String addAccount,String subAccount,int money) throws Exception {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql:///atguigu", "root", "123456");
try{
//关闭自动提交
connection.setAutoCommit(false);
BankDao bankDao = new BankDao();
bankDao.add(addAccount,money,connection);
System.out.println("加钱成功");
System.out.println("-------------------------");
System.out.println("减钱成功");
bankDao.sub(subAccount,money,connection);
//事务提交
connection.commit();
}catch (Exception e){
connection.rollback();
throw e;
}
}
}