java語言MySQL資料庫事務的處理

來源:互聯網
上載者:User

標籤:java語言mysql資料庫交易處理

交易處理流程

1、屏蔽自動認可功能

2、處理事務

3、恢複自動認可功能

代碼執行個體

執行程式之前資料表的樣子


import java.sql.*;public class GetConnection{public static void main(String[] args){Access2Database adb=new Access2Database();Connection conn=adb.getConn();//transaction dealingPreparedStatement pstam=null;try{conn.setAutoCommit(false);String sql="delete from student where name='a' and major=?";pstam=conn.prepareStatement(sql);pstam.setString(1, "Chinese");pstam.executeUpdate();
<span style="white-space:pre"></span><pre name="code" class="java"><span style="white-space:pre"></span>conn.rollback();

<span style="white-space:pre"></span>conn.commit();}catch(SQLException e){try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}e.printStackTrace();}finally{try {conn.setAutoCommit(true);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//release the resource of the programtry{pstam.close();conn.close();}catch(SQLException e){e.printStackTrace();}}}
之後的樣子


可見沒有發生改變,交易回復成功

======================================================================

除此應用外,還可以儲存交易處理的中間態,最後可以恢複到此中間儲存狀態

資料表之前的狀態


看代碼

import java.sql.*;public class GetConnection{public static void main(String[] args){Access2Database adb=new Access2Database();Connection conn=adb.getConn();//transaction dealingPreparedStatement pstam=null;try{conn.setAutoCommit(false);String sql="delete from student where name='a' and major=?";pstam=conn.prepareStatement(sql);pstam.setString(1, "Chinese");pstam.executeUpdate();//conn.commit();Savepoint sp=conn.setSavepoint();sql="insert into student(name,major,score) values('g','Math','99');";pstam=conn.prepareStatement(sql);pstam.executeUpdate();conn.rollback(sp);conn.commit();}catch(SQLException e){try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}e.printStackTrace();}finally{try {conn.setAutoCommit(true);} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//release the resource of the programtry{pstam.close();conn.close();}catch(SQLException e){e.printStackTrace();}}}





java語言MySQL資料庫事務的處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.