日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

事务概念

發布時間:2024/9/16 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 事务概念 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

?

@Testpublic?void?testSaveMoney(){Connection?conn?=null;PreparedStatement?pstmt?=?null;String?accountId="123456789";double?money??=100;ResultSet?rs?=?null;String?sql?=?"Insert?into?inaccount?(accountid,inbalance)?values(?,?)";try?{conn?=?DBUtil.getCon();pstmt?=?conn.prepareStatement(sql);pstmt.setString(1,?accountId);pstmt.setDouble(2,?money);pstmt.executeUpdate();sql?=?"update?account?set?balance=balance+??where?accountid=?";pstmt?=?conn.prepareStatement(sql);pstmt.setDouble(1,?money);pstmt.setString(2,?accountId);boolean?flag?=?true;if(flag){throw?new?SQLException("因網絡或不明原因出異常!");}pstmt.executeUpdate();}?catch?(Exception?e)?{//?TODO?Auto-generated?catch?blocke.printStackTrace();}finally{DBUtil.close(conn,?pstmt,?rs);}}

如果不使用事務操作,對于一個銀行業務來說是致命的,上面的這個示例,造成的結果就是一個inaccount表中會插入一條數據,而account表中沒有任何改變。

事務的類型:

  • 自動提交:執行update馬上保存數據

  • 手動提交:執行update不保存數據,先放入緩存,只有執行Commit,才保存

  • 設置事務:

    ?

    @Testpublic?void?testSaveMoney(){Connection?conn?=null;PreparedStatement?pstmt?=?null;String?accountId="123456789";double?money??=100;ResultSet?rs?=?null;String?sql?=?"Insert?into?inaccount?(accountid,inbalance)?values(?,?)";try?{conn?=?DBUtil.getCon();conn.setAutoCommit(false);pstmt?=?conn.prepareStatement(sql);pstmt.setString(1,?accountId);pstmt.setDouble(2,?money);pstmt.executeUpdate();sql?=?"update?account?set?balance=balance+??where?accountid=?";pstmt?=?conn.prepareStatement(sql);pstmt.setDouble(1,?money);pstmt.setString(2,?accountId);boolean?flag?=?true;if(flag){throw?new?SQLException("因網絡或不明原因出異常!");}pstmt.executeUpdate();//提交事務conn.commit();}?catch?(Exception?e)?{//?TODO?Auto-generated?catch?block//回滾事務,回滾到conn.setAutoCommit(false);try?{conn.rollback();}?catch?(SQLException?e1)?{//?TODO?Auto-generated?catch?blocke1.printStackTrace();}e.printStackTrace();}finally{DBUtil.close(conn,?pstmt,?rs);}}

    ?

    在事務沒有提交之前,數據時先放到緩存中的,但是事務提交時會將數據保存到表中并清空緩存,rollback的原理也是清空緩存這樣就不會出現上面的問題

    ?

    總結

    以上是生活随笔為你收集整理的事务概念的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。