JDBC事务机制

概述

1、JDBC中的事务是自动提交的,只要执行任意一条DML语句就自动提交一次。
2、这是JDBC默认的事务行为,但是在实际的业务当中,通常都是N条DML语句共同联合才能完成的,必须保证他们这些DML语句在同一个事务中同时成功或者同时失败。

相关方法

1、void setAutoCommit(boolean autoCommit)
(java.sql.Connection)
将此连接的自动提交模式设置为给定状态。
autoCommit - true启用自动提交模式; false禁用它。
2、void commit()
(java.sql.Connection)
使自上次提交/回滚以来所做的所有更改都将永久性,并释放此Connection对象当前持有的任何数据库锁。只有当自动提交模式被禁用时,才应该使用此方法。
3、void rollback()
(java.sql.Connection)
撤消在当前事务中所做的所有更改,并释放此 Connection对象当前持有的任何数据库锁。只有当自动提交模式被禁用时,才应该使用此方法。

转账示例

  • 原数据
    JDBC事务机制
  • 代码
import java.sql.*;
import java.util.ResourceBundle;

public class Demo {
    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("jdbc.info");
        String driver = bundle.getString("driver");
        String url = bundle.getString("url");
        String user = bundle.getString("user");
        String password = bundle.getString("password");

        Connection conn = null;
        PreparedStatement pstmt = null;
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);

            /*将自动提交机制改为手动提交*/
            conn.setAutoCommit(false);
            String sql = "update t_act set balance=? where actno=?";

            pstmt = conn.prepareStatement(sql);
            pstmt.setDouble(1,10000);
            pstmt.setInt(2,111);
            int count = pstmt.executeUpdate();
            
            pstmt.setDouble(1,10000);
            pstmt.setInt(2,222);
            count += pstmt.executeUpdate();

            System.out.println(count==2 ? "转账成功" : "转账失败");

            /*程序到这儿证明没有异常,
            事务结束,手动提交*/
            conn.commit();
        }catch (SQLException | ClassNotFoundException e){
            /*回滚事务*/
            if (conn != null) {
                try {
                    conn.rollback();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            e.printStackTrace();
        }finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

JDBC事务机制
JDBC事务机制

相关推荐