//采用事务处理转账失败的情况 @Test public void testTransaction1() throws Exception { // 获得链接对象 Connection conn = JdbcUtils.getConnection(); PreparedStatement pstmt = null ; PreparedStatement pstmt1 = null ; //让数据库不要自动提交事务 conn.setAutoCommit(false) ; try{ pstmt = conn.prepareStatement("update bank set money = money -? where id = ?") ; pstmt.setFloat(1, 2000) ; pstmt.setInt(2, 1) ; int n = pstmt.executeUpdate() ; System.out.println(n); System.out.println(10/2); pstmt1 = conn.prepareStatement("update bank set money = money + ? where id = ?") ; pstmt1.setFloat(1, 2000) ; pstmt1.setInt(2, 2) ; int n1 = pstmt1.executeUpdate() ; System.out.println(n1); //手动进行提交,体现一致性 conn.commit() ; }catch(Exception e){ //让事务进行回滚 conn.rollback() ; } // 释放资源 JdbcUtils.release(null, pstmt, conn); JdbcUtils.release(null, pstmt1, conn); }
注意!!!
mysql中的表要使用innodb引擎才能使用事务回滚功能!