JDBC事务

以经典的转账业务举例

创建数据库


Create Table

CREATE TABLE `t_bank` (
  `id` int NOT NULL AUTO_INCREMENT,
  `account` varchar(20) DEFAULT NULL,
  `money` int unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

插入两条数据
在这里插入图片描述
新建一个transaction包
在这里插入图片描述

BankDao

package com.transaction;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * bank表的数据库操作方法存储类
 */
public class BankDao {
	/**
	 * 加钱的方法
	 * @param account
	 * @param money
	 * @param connection
	 */
	public void add(String account, int money, Connection connection) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		//Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");

		String sql = "update t_bank set money = money + ? where account = ?";
		PreparedStatement statement = connection.prepareStatement(sql);

		statement.setObject(1, money);
		statement.setObject(2, account);
		statement.executeUpdate();

		statement.close();
		System.out.println("加钱成功!");

	}

	/**
	 * 减钱的方法
	 * @param account
	 * @param money
	 * @param connection
	 */
	public void sub(String account, int money, Connection connection) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		//Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");

		String sql = "update t_bank set money = money - ? where account = ?";

		PreparedStatement statement = connection.prepareStatement(sql);

		statement.setObject(1, money);
		statement.setObject(2, account);
		statement.executeUpdate();

		statement.close();

		System.out.println("减钱成功!");
	}

}

BankService

package com.transaction;

import org.junit.jupiter.api.Test;

import java.sql.Connection;
import java.sql.DriverManager;

public class BankService {
	/**
	 * 转账的方法
	 * @param addAccount
	 * @param subAccount
	 * @param money
	 */
	public void transfer(String addAccount, String subAccount, int money) throws Exception {
		Class.forName("com.mysql.cj.jdbc.Driver");
		Connection connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "123456");
		BankDao bankDao = new BankDao();
		try {
			// 关闭自动提交
			connection.setAutoCommit(false);
			bankDao.add(addAccount, money, connection);
			bankDao.sub(subAccount, money, connection);
			System.out.println("转账完成!");
			connection.commit();
		} catch (Exception e){
			connection.rollback();
			throw e;
		} finally {
			connection.close();
		}
	}
	@Test
	public void start() throws Exception {
		transfer( "lvdd", "ergouzi",500);
	}
}

运行结果

加钱成功!
减钱成功!
转账完成!

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值