JDBC之转账操作(运用事务)

若是普通的转账操作我们能想到的就是运用两次update

	public static void transferAccounts(int id1,int id2,int money)//id为id1的人向id为id2的人转账money元
	{
		Connection con=null;
		PreparedStatement pstmt1=null;
		PreparedStatement pstmt2=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();
			String sql="update student set money=money-? where id=?";
			pstmt1=con.prepareStatement(sql);
			pstmt1.setInt(1, money);
			pstmt1.setInt(2, id1);
			pstmt1.executeUpdate();
			//String s=null;
			//s.charAt(2); 这是我们设置的错误,若不用事务,便会发现数据库中的money只有减少,没有增加
			sql="update student set money=money+? where id=?";
			pstmt2=con.prepareStatement(sql);
			pstmt2.setInt(1, money);
			pstmt2.setInt(2, id2);
			pstmt2.executeUpdate();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, pstmt1, rs);
			try {
				pstmt2.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}

但是这种操作是有缺点的,比如当id1的money减少后,在id2的money还未增加前发生了不知名错误,从而导致下面的代码都无法执行,那么就会导致不好的后果,类似于银行存取钱,我们把钱存到银行去,但账户上没变,那岂不是很荒谬?
因此要解决这个问题,我们运用事务。即将这两个操作连在一起,这两个操作要么全都执行,要么全都不执行,具体代码如下:

//关键语句只有两句
con.setAutoCommit(false);//开启事务
con.commit();//提交事务
//将我们想要连接在一起的操作放在这两行代码之间

完整代码如下:

public static void transferAccounts(int id1,int id2,int money)//id为id1的人向id为id2的人转账money元
	{
		Connection con=null;
		PreparedStatement pstmt1=null;
		PreparedStatement pstmt2=null;
		ResultSet rs=null;
		try {
			con=JDBCUtils.getConnection();
			con.setAutoCommit(false);//开启事务
			String sql="update student set money=money-? where id=?";
			pstmt1=con.prepareStatement(sql);
			pstmt1.setInt(1, money);
			pstmt1.setInt(2, id1);
			pstmt1.executeUpdate();
			
			sql="update student set money=money+? where id=?";
			pstmt2=con.prepareStatement(sql);
			pstmt2.setInt(1, money);
			pstmt2.setInt(2, id2);
			pstmt2.executeUpdate();
			con.commit();//提交事务

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JDBCUtils.close(con, pstmt1, rs);
			try {
				pstmt2.close();
			} catch (Exception e2) {
				// TODO: handle exception
			}
		}
	}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

henulmh

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值