事務處理-回滾(轉帳操做)

JDBC事務處理-四大原則java

原子性
一致性
隔離性
持久性sql

 

第一步:實現轉帳操做數據庫

假設在帳戶中,蓋倫有餘額5000元,趙信有餘額2000元,函數

蓋倫要向趙信轉帳1000元。blog

	public static void outMoney(Connection conn,String name,int account) throws SQLException{
		String sql="update t_account set balance=balance-? where name=?";
		PreparedStatement pst=conn.prepareStatement(sql);
		pst.setInt(1, account);
		pst.setString(2, name);
		int result=pst.executeUpdate();
		pst.close();
	}
	public static void inMoney(Connection conn,String name,int account) throws SQLException{
		String sql="update t_account set balance=balance+? where name=?";
		PreparedStatement pst=conn.prepareStatement(sql);
		pst.setInt(1, account);
		pst.setString(2, name);
		int result=pst.executeUpdate();
		pst.close();
	}

  

		System.out.println("蓋倫正在給趙信轉帳1000元");
		//轉帳操做
		try {
			outMoney(conn,"蓋倫",1000);
			inMoney(conn,"趙信",1000);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				System.out.println("轉帳成功!");
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

  運行:事務

正常轉帳成功。get

假設  public static void inMoney(Connection conn,String name,int account)運行時出現意外。it

人爲構造意外io

而後運行程序class

 

 

查看數據庫的數據

蓋倫少了1000元,趙信餘額沒有變!

這樣,趙信就坑了!!!

 

【改進】

所須要的函數

con.setAutoCommit(false); // 取消自動提交

con.rollback(); // 回滾

con.commit(); // 提交事務

 

             Connection conn=null;
		try {
			conn = dbUtil.getConnection();
			System.out.println("蓋倫正在給趙信轉帳1000元");
			conn.setAutoCommit(false);//取消自動提交
			outMoney(conn,"蓋倫",1000);
			inMoney(conn,"趙信",1000);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			try {
				conn.rollback();//回滾
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			try {
				conn.commit();//提交
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}    
相關文章
相關標籤/搜索