jdbc事务使用例子

本地事务处理实例
 public void transferAccount() { 
		 Connection conn = null; 
		 Statement stmt = null; 
		 try{ 
			 conn = getDataSource().getConnection(); 
			 // 将自动提交设置为 false,
			 //若设置为 true 则数据库将会把每一次数据更新认定为一个事务并自动提交
			 conn.setAutoCommit(false);
			
			 stmt = conn.createStatement(); 
			 // 将 A 账户中的金额减少 500 
			 stmt.execute("\
             update t_account set amount = amount - 500 where account_id = 'A'");
			 // 将 B 账户中的金额增加 500 
			 stmt.execute("\
             update t_account set amount = amount + 500 where account_id = 'B'");
			
			 // 提交事务
		     conn.commit();
			 // 事务提交:转账的两步操作同时成功
		 } catch(SQLException sqle){ 			
			 try{ 
				 // 发生异常,回滚在本事务中的操做
                conn.rollback();
				 // 事务回滚:转账的两步操作完全撤销
                 stmt.close(); 
                 conn.close(); 
			 }catch(Exception ignore){ 
				
			 } 
			 sqle.printStackTrace(); 
		 } 
	 }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章