JDBC事务(实例)

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

import JDBC.SqlHelper;

public class TransactionDemo {
	/*
	 * 事务四大特性:原子性:事务的执行要么都成功,要么都失败,回滚。
	 * 一致性:事务的处理要保持一致性
	 * 隔离性:事务要排队
	 * 持久性:事务一旦提交,必须完成。
	 */

	public static void main(String[] args) {
		CheckAccount();
		String payId = "3";
		String reId = "2";
		int money = 10000;
		pay(payId, reId, money);
		System.out.println("-------------------------------");
		CheckAccount();
	}
	public static void pay(String payId, String reId, int money) {
		Connection conn = null;
		try {
			conn = SqlHelper.getConnection();
			conn.setAutoCommit(false);  // 取消自动提交
			// 先判断账户余额是否足够, 不够则抛出异常
			String searchSql = "SELECT salary FROM jdbc_table_3 WHERE id = ?";
			PreparedStatement ps = conn.prepareStatement(searchSql);
			ps.setString(1, payId);
			ResultSet rs = ps.executeQuery();
			rs.next();
			if(money > rs.getInt("salary")) {
				throw new Exception("账户余额不足!");
			}
			rs.close();
			ps.close();
			
			// 进行转账操作
			String paySql = "UPDATE jdbc_table_3 "
					+ "SET salary = salary + ? "
					+ "WHERE id = ?";
			PreparedStatement ps1 = conn.prepareStatement(paySql);
			ps1.setInt(1, -money);
			ps1.setString(2, payId);
			int n = ps1.executeUpdate();
			if(n != 1) {
				throw new Exception("账号可能不唯一!");
			}
			
			ps1.setInt(1, money);
			ps1.setString(2, reId);
			int n1 = ps1.executeUpdate();
			if(n1 != 1) {
				throw new Exception("账号可能不唯一!");
			}
			ps1.close();
			
			conn.commit(); // 事务的提交
			
			
		}catch(Exception e) {
			e.printStackTrace();
			SqlHelper.rollback(conn);
		}finally {
			SqlHelper.close(conn);
		}
	}
	
	public static void CheckAccount() {
		Connection conn = null;
		try {
			conn = SqlHelper.getConnection();
			String Sql = "SELECT * FROM jdbc_table_3";
			PreparedStatement ps = conn.prepareStatement(Sql);
			ResultSet rs = ps.executeQuery();
			while(rs.next()) {
				System.out.println("id:" + rs.getString("id") + "    name:" + rs.getString("name") + "    salary:" + rs.getInt("salary"));
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			SqlHelper.close(conn);
		}
	}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值