• JDBC 事务(二)回滚到保存点


    public class SavePointTest {

        /**
         * @param args
         * @throws SQLException
         */
        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);
            }
        }
    }

  • 相关阅读:
    jchdl
    jchdl
    UVa 11134 (区间上的贪心) Fabled Rooks
    UVa (二分) 11627 Slalom
    POJ 1037 (计数 + DP) 一个美妙的栅栏
    HDU 3448 Bag Problem
    HDu 3449 (有依赖的01背包) Consumer
    POJ 1456 (贪心+并查集) Supermarket
    POJ 2236 (简单并查集) Wireless Network
    POJ 1703 Find them, Catch them
  • 原文地址:https://www.cnblogs.com/flying607/p/3461224.html
Copyright © 2020-2023  润新知