标签: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