JDBC控制事务

1. 事务:一个包含多个步骤的业务操作。如果这个业务操作被事务管理,则这多个步骤要么同时成功,要么同时失败。

    2. 操作:

        1. 开启事务

        2. 提交事务

        3. 回滚事务

3. 使用Connection对象来管理事务

        开启事务:setAutoCommit(boolean autoCommit) :调用该方法设置参数为false,即开启事务

            在执行sql之前开启事务

        提交事务:commit()

            当所有sql都执行完提交事务

        回滚事务:rollback()

             在catch中回滚事务

4.代码

account表

package my;

import we.JDBCTool;

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

/*
* 编写一个转账的程序
* */
public class JDBCDemo6 {
    public static void main(String[] args) {
        JDBCTool tool = new JDBCTool();
        Connection conn = null;
        PreparedStatement preparedStatement1 = null;
        PreparedStatement preparedStatement12 = null;

        try {
            tool.getDriver();
            conn = tool.getConnection();
            String sql1 = "update account set balance=balance-? where id=?";
            String sql2 = "update account set balance=balance+? where id=?";
            conn.setAutoCommit(false);
            preparedStatement1 = conn.prepareStatement(sql1);
            preparedStatement12 = conn.prepareStatement(sql2);
            preparedStatement1.setDouble(1, 500);
            preparedStatement1.setInt(2, 1);
            preparedStatement12.setDouble(1, 500);
            preparedStatement12.setInt(2, 2);
            preparedStatement1.executeUpdate();
            //手动制造异常
            int i = 5 / 0;
            preparedStatement12.executeUpdate();
            //提交事务
            conn.commit();//若成功提交,则返回值为null

        } catch (SQLException e1) {
            try {
                if (conn != null)
                    conn.rollback();


            } catch (SQLException e) {
                e.printStackTrace();
            }
            e1.printStackTrace();
        } finally {
            tool.getClose(null, preparedStatement12, null);
            tool.getClose(conn, preparedStatement1, null);
        }

    }
    
    }

猜你喜欢

转载自blog.csdn.net/dreame_life/article/details/87888719