1、屏蔽自動提交功能
2、處理事務(wù)
3、恢復(fù)自動提交功能
代碼實例
執(zhí)行程序之前數(shù)據(jù)表的樣子
public class GetConnection{ public static void main(String[] args){ Access2Database adb=new Access2Database(); Connection conn=adb.getConn(); //transaction dealing PreparedStatement 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 block e1.printStackTrace(); } e.printStackTrace(); }finally{ try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //release the resource of the program try{ pstam.close(); conn.close(); }catch(SQLException e){ e.printStackTrace(); } } }
可見沒有發(fā)生改變,事務(wù)回滾成功
======================================================================
除此應(yīng)用外,還可以保存事務(wù)處理的中間態(tài),最后可以恢復(fù)到此中間保存狀態(tài)
數(shù)據(jù)表之前的狀態(tài)
看代碼
import java.sql.*; public class GetConnection{ public static void main(String[] args){ Access2Database adb=new Access2Database(); Connection conn=adb.getConn(); //transaction dealing PreparedStatement 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 block e1.printStackTrace(); } e.printStackTrace(); }finally{ try { conn.setAutoCommit(true); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //release the resource of the program try{ pstam.close(); conn.close(); }catch(SQLException e){ e.printStackTrace(); } } }
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com