日期:2014-05-16  浏览次数:20423 次

Java JDBC基础(四)

?1.全局事务与还原点测试

package com.yli.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;

/**
 * 全局事务与还原点测试
 */
public class TransactionTest {

    public static void main(String[] args) {

        // Test1();

        Test2();
    }

    /**
     * 不创建还原点回滚:即全局回滚
     */
    public static void Test1() {
        try {
            Connection conn;
            conn = ConnectionUtil.getConnection();

            // Connection默认全局事务为自动提交
            // 实则false则需要手动提交
            conn.setAutoCommit(false);

            // PreparedStatement[update]
            String sql = "update ES_T_SHOP_AFFICHE set AFFICHETITLE='iteye' where AFFICHEID=?";
            PreparedStatement preStat = conn.prepareStatement(sql);
            preStat.setInt(1, 100000493);
            preStat.executeUpdate();

            try {
                int a = 10 / 0;
                System.out.println(a);

                // 如果运行都正确:提交,一旦提交回滚也没有用
                conn.commit();
            } catch (ArithmeticException e) {
                e.printStackTrace();

                // 如果遇到错误,比如除以0:回滚
                conn.rollback();
            }

            ConnectionUtil.close(conn);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建还原点回滚:回滚到还原点
     */
    public static void Test2() {
        try {
            Connection conn;
            conn = ConnectionUtil.getConnection();

            // Connection默认全局事务为自动提交
            // 实则false则需要手动提交
            conn.setAutoCommit(false);

            // PreparedStatement[update]
            String sql = "update ES_T_SHOP_AFFICHE set AFFICHETITLE='suning' where AFFICHEID=?";
            PreparedStatement preStat = conn.prepareStatement(sql);
            preStat.setInt(1, 100000493);
            preStat.executeUpdate();

            // 创建还原点
            Savepoint savePoint1 = conn.setSavepoint("savePoint1");

            sql = "update ES_T_SHOP_AFFICHE set AFFICHETITLE='hello' where AFFICHEID=?";
            preStat = conn.prepareStatement(sql);
            preStat.setInt(1, 100000496);
            preStat.executeUpdate();

            if (true) {
                // 回滚到第一个还原点,表示从一开始执行到该还原点的事务都会正常提交
                // 而从该还原点之后执行的事务,都会回滚掉
                conn.rollback(savePoint1);
            }

            // 释放还原点
            conn.releaseSavepoint(savePoint1);

            // 最后必须要提交,只是还原点以后执行的SQL都不会提交
            conn.commit();
            
            ConnectionUtil.close(conn);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

?

?