码迷,mamicode.com
首页 > 其他好文 > 详细

事务处理-回滚(转账操作)

时间:2016-12-08 09:41:34      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:nts   highlight   nal   构造   auto   分享   div   处理   com   

JDBC事务处理-四大原则

原子性
一致性
隔离性
持久性

 

第一步:实现转账操作

技术分享

假设在账户中,盖伦有余额5000元,赵信有余额2000元,

盖伦要向赵信转账1000元。

	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();
			}
		}

  运行:

技术分享

技术分享

正常转账成功。

假设  public static void inMoney(Connection conn,String name,int account)运行时出现意外。

人为构造意外

技术分享

然后运行程序

 

技术分享

 

查看数据库的数据

技术分享

盖伦少了1000元,赵信余额没有变!

这样,赵信就坑了!!!

 

【改进】

所需要的函数

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

con.rollback(); // 回滚

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

 

事务处理-回滚(转账操作)

标签:nts   highlight   nal   构造   auto   分享   div   处理   com   

原文地址:http://www.cnblogs.com/void-m/p/6143540.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!