Introduction to the basic operations of JDBC transactions

Introduction

If A and B are the same transaction operation, when the A operation is completed, the database etc. encounter some exceptions and cannot complete the B operation. At this time, the system will automatically delete the completed operation to avoid loss. Ensure that multiple operations on the database either all succeed or all fail.

For example

Question: Suppose, in a bank management system, A transfers money to B, and A has just transferred out. At this time, there is a power outage or a database crash. The money transfer operation of A has been completed at this time, but the money collection operation of B has not been performed. At this time there will be trouble

Demo

Open transaction : con.setAutoCommit(false); true automatic commit false manual commit
commit transaction (manual commit) : con.commit(); operations between opening a transaction and committing a transaction are all transaction operations, if any operation is executed during the period Success, all operations during the period are invalid

public static void  transferAccounts(String usernameOne,String usernameTwo,int money) {
    
    
		Connection con = null;
		PreparedStatement pstmtOne = null;
		PreparedStatement pstmtTwo = null;
		ResultSet rs = null;
		try {
    
    
			con = DBCPDateSource.getConnection();
	
			con.setAutoCommit(false);		//开启事务  true自动提交  false手动提交
			
			String sqlOne = "UPDATE user SET balance=balance-? WHERE username=?";
			pstmtOne=con.prepareStatement(sqlOne);
			pstmtOne.setInt(1, money);
			pstmtOne.setString(2,usernameOne);
			pstmtOne.executeUpdate();
			
			//假设代码进行到此处时,程序中断,这里用一个隐式异常来模拟
			//String s =null;
			//获取s索引为2的内容
		    //s.charAt(2);
		    //此时你会发现数据库中,转钱的人钱已减少,但是收钱的人却没有收到
		    //如果要解决这种问题,就需要用到事务去避免   通过con.setAuToCommit()开启事务
			
			String sqlTwo = "UPDATE user SET balance=balance+? WHERE username=?";
			pstmtTwo=con.prepareStatement(sqlTwo);
			pstmtTwo.setInt(1, money);
			pstmtTwo.setString(2,usernameTwo);
		    pstmtTwo.executeUpdate();
		    
		    con.commit();//提交事务    开启事务与提交事务之间的操作都为事务操作,如果期间有任何操作为执行成功,则期间所有的操作都无效
			
		}catch(Exception e) {
    
    
			e.printStackTrace();		
		}finally {
    
    
			//因为此时我们需要关闭两个pstmt,传递两个pstmt参数,所以我们需要完善我们的工具类
			DBCPDateSource.close(pstmtTwo, pstmtTwo, con);
		}
	}

Guess you like

Origin blog.csdn.net/zhang19903848257/article/details/107149275