JDBC转账事物

 一、总体设计

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;
        }




    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值