`

JDBC事务保存点,即事部分回滚

阅读更多

JDBC中的事务保存点,即事务发生回滚的时候,回滚到保存点那里去,事务开始到保存点之间的操作不用回滚.

事务(SavePoint)

l       当只想撤销事务中的部分操作时可使用SavePoint

l       SavePoint sp = connection.setSavepoint();

l       connection.rollerbak(sp); //回滚到那个事务点上去

l       connection.commit();

 

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Savepoint;

import java.sql.Statement;

 

public class SavePointTest {

    public static void main(String[] args) throws SQLException {

       test();

    }

 

    static void test() throws SQLException {

       Connection conn = null;

       Statement st = null;

       ResultSet rs = null;

       Savepoint sp = null;

       try {

           conn = JdbcUtils.getConnection();

           conn.setAutoCommit(false);        

           st = conn.createStatement();

           String sql = "update user set money=money-10 where id=1";

           st.executeUpdate(sql);

           sp = conn.setSavepoint();

 

           sql = "update user set money=money-10 where id=3";

           st.executeUpdate(sql);

 

           sql = "select money from user where id=2";

           rs = st.executeQuery(sql);

           float money = 0.0f;

           if (rs.next()) {

              money = rs.getFloat("money");

           }

           if (money > 300)

              throw new RuntimeException("已经超过最大值!");

 

           sql = "update user set money=money+10 where id=2";

           st.executeUpdate(sql);

 

           conn.commit();

       } catch (RuntimeException e) {

           if (conn != null && sp != null) {

              conn.rollback(sp);//回滚到那个事务点上去

              conn.commit();

           }

           throw e;

       } catch (SQLException e) {

           if (conn != null)

              conn.rollback();

           throw e;

       } finally {

           JdbcUtils.free(rs, st, conn);

       }

    }

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics