(JDBC)21_事务的保存点处理

使用保存点,设置回滚时需要到的点

public class TxTest {
    public static void main(String[] args) throws SQLException {
        test();
    }

    static void test() throws SQLException {
        System.out.println("123");
        Connection con = get_con();
        Savepoint sp = null;
        try {
            Statement st = con.createStatement();

            con.setAutoCommit(false);

            String sql = "update usertr set money=money-10 where id=4";
            st.executeUpdate(sql);
            sp = con.setSavepoint();// 设置保存点,回滚的时候滚到这里

            sql = "update usertr set money=money-10 where id=1";
            st.executeUpdate(sql);
            sql = "select money from usertr where id=2";
            ResultSet rs = st.executeQuery(sql);

            int money = 0;
            if (rs.next()) {
                money = rs.getInt("money");
                System.out.println(money);
            }

            if (money > 100) {// 即第二个人的钱多余100就不转账
                throw new RuntimeException("多了");
            }
            sql = "update usertr set money=money+10 where id=2";
            st.executeUpdate(sql);

            con.commit();
            con.close();
            rs.close();
            st.close();

        } catch (RuntimeException e) {
            con.rollback(sp);
            con.commit();
            throw e;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            if (con != null) {
                con.rollback();
            }
            throw e;
        }

    }

    static Connection get_con() {
        Connection con = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/new_schema", "root", "zxy123456");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return con;
    }

}

 

posted @ 2017-07-19 09:55  z_dominic  阅读(192)  评论(0编辑  收藏  举报