`

JDBC事务处理

阅读更多

在JDBC中怎样将多个SQL语句组合成一个事务呢?在JDBC中,打开一个连接对象Connection时,缺省是auto-commit模式,每个 SQL语句都被当作一个事务,即每次执行一个语句,都会自动的得到事务确认。为了能将多个SQL语句组合成一个事务,要将auto-commit模式屏蔽 掉。在auto-commit模式屏蔽掉之后,如果不调用commit()方法,SQL语句不会得到JDBC事务处理确认。在最近一次commit()方 法调用之后的所有SQL会在方法commit()调用时得到确认。

    public int delete(int sID) {   
    dbc = new DataBaseConnection();   
     Connection con = dbc.getConnection();   
     try {   
    con.setAutoCommit(false);// 更改JDBC事务的默认提交方式   
    dbc.executeUpdate("delete from bylaw where ID=" + sID);   
    dbc.executeUpdate("delete from bylaw _content where ID=" + sID);   
    dbc.executeUpdate("delete from bylaw _affix where bylawid=" + sID);   
    con.commit();//提交JDBC事务   
   con.setAutoCommit(true);// 恢复JDBC事务的默认提交方式   
   dbc.close();   
   return 1;   
    }   
   catch (Exception exc) {   
   con.rollBack();//回滚JDBC事务   
   exc.printStackTrace();   
   dbc.close();   
   return -1;   
    }   
   }  

 

A sequence diagram showing a component transaction and its persistence transaction:

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics