事物 银行转账 回滚

事务

转账

      ACCID PASSWORD             USERNAME             OPENDATE         BALANCE
----------- -------------------- -------------------- ----------- ------------
      10086 123456               中国移动             2019/7/12 1    110100.00
      10010 789000               中国财经             2019/7/18 1     20000.00

public static void main(String[] args) throws Exception {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		String url = "jdbc:oracle:thin:@//localhost:1521/ORCL";
		String user = "scott";
		String password = "123";
		Connection conn = DriverManager.getConnection(url, user, password);

		conn.setAutoCommit(false);// 自动提交方式设置为false
		try {
			String sql1 = "update account set balance=balance-10000 where accid=10010";
			String sql2 = "update account set balance=balance+10000 where accid=10086";
			PreparedStatement ps = conn.prepareStatement(sql1);
			ps.executeUpdate();
			ps = conn.prepareStatement(sql2);
		    ps.executeUpdate();
			conn.commit();// 如果没有异常,直接提交
			System.out.println("转账成功");
		} catch (Exception e) {
			e.printStackTrace();
			conn.rollback();// 执行失败,回滚
			System.out.println("转账失败");
		} finally {
			conn.close();
		}
	}

      ACCID PASSWORD             USERNAME             OPENDATE         BALANCE
----------- -------------------- -------------------- ----------- ------------
      10086 123456               中国移动             2019/7/12 1    120100.00
      10010 789000               中国财经             2019/7/18 1     10000.00
上一篇:MySQL事务隔离级别----Read uncommitted(读未提交)


下一篇:Entity Framework应用:使用Code First模式管理事务