事务处理-回滚(转账操作)(转自http://www.cnblogs.com/void-m/p/6143540.html)

JDBC事务处理-四大原则

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

 

第一步:实现转账操作

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

盖伦要向赵信转账1000元。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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();
}

  

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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(); // 提交事务

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
      Connection conn= null ;
try  {
     conn = dbUtil.getConnection();
     System.out.println( "盖伦正在给赵信转账1000元" );
     conn.setAutoCommit( false ); //取消自动提交
     outMoney(conn, "盖伦" , 1000 );
     inMoney(conn, "赵信" , 1000 );
catch  (ClassNotFoundException e) {
     e.printStackTrace();
catch  (SQLException e) {
     try  {
         conn.rollback(); //回滚
     catch  (SQLException e1) {
         e1.printStackTrace();
     }
     e.printStackTrace();
} finally {
     try  {
         conn.commit(); //提交
         conn.close();
     catch  (SQLException e) {
         e.printStackTrace();
     }

转载于:https://www.cnblogs.com/AnswerTheQuestion/p/6253828.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值