zoukankan      html  css  js  c++  java
  • 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);
            }
        }
    }

  • 相关阅读:
    打印机无法访问打印机怎么连
    IDEA 2018 LICENSE SERVER
    idea 项目打包发布
    Oracle的关于小数的使用
    js代码实现购物车效果
    通过shell定时备份数据库
    (二)Linux实操之——网络配置、进程管理、服务管理、组管理、YUM
    (一)Linux实操之——权限、任务调度、磁盘分区
    idea搭建简易ssm项目
    idea右键无法新建Java Class
  • 原文地址:https://www.cnblogs.com/flying607/p/3461224.html
Copyright © 2011-2022 走看看