• 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);
            }
        }
    }

  • 相关阅读:
    isNUll ,对于sql中的一个表的description的NULL和空格的处理
    Thread类学习
    java学习计划
    HTTP请求过程(http是一种无状态协议,即不建立持久的连接)
    JS事件流(W3C与IE区别)
    学习Javascript闭包
    div内长串数字或字母不断行处理
    仿购物车加减数字
    多行文字两行断尾点点点显示
    MegaCli命令详解
  • 原文地址:https://www.cnblogs.com/flying607/p/3461224.html
Copyright © 2020-2023  润新知