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

來源:互聯網
上載者:User

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

交易處理流程

1、屏蔽自動認可功能

2、處理事務

3、恢複自動認可功能

代碼執行個體

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


<pre name="code" class="java">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.rollback();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();}}}


相關文章

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.