jdbc--事务

事务

事务的出现是为了防止一个由两个人交互的事情,出现不同的结果,把两个或多个步骤看成一个步骤,
如果有任意一方没有满足,则视为事务终止=没做

执行前

jdbc--事务

jdbc--事务

执行后

jdbc--事务

为了防止这样的事情发生出现了事务

package cn.usts.edu.jdbc.rollback;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * @author :fly
 * @description: 事务操作
 *                  B转钱给A100块
 * @date :2021/11/6 12:13
 */
public class RollbackDemo {

    public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
        Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
        Driver driver =(Driver) aClass.newInstance();
        try {
            DriverManager.registerDriver(driver);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        FileInputStream fileInputStream = new FileInputStream("D:\\all_projects\\java_projects\\java_ij\\springMVC\\Jdbc\\src\\cn\\usts\\edu\\config\\db.properties");
        Properties properties = new Properties();
        properties.load(fileInputStream);
        Connection connection = null;
        try {
            connection = DriverManager.getConnection((String) properties.get("url"), (String) properties.get("user"), (String) properties.get("password"));

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

        String sql1 = "UPDATE `persons`.`money` SET `money` = 1400+100 WHERE `name` = 'A'";
        String sql2 = "UPDATE `persons`.`money` SET `money` = 1400-100 WHERE `name` = 'B'";


        PreparedStatement preparedStatement = null;
        PreparedStatement preparedStatement1 = null;
        try {
            connection.setAutoCommit(false);// 默认自动提交,我们设置不自动提交

            preparedStatement = connection.prepareStatement(sql1);
            preparedStatement.executeUpdate();

            int i=1/0;

            preparedStatement1 = connection.prepareStatement(sql2);
            preparedStatement1.executeUpdate();

            //提交事务
            connection.commit();
        } catch (SQLException e) {
            System.out.println("事务回滚了");
            connection.rollback();//回滚

        }

        // 关闭
        try {
            preparedStatement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }


    }

}

  • 关闭自动提交 connection.setAutoCommit(false)
  • 捕获异常 try catch
  • 最后提交 connection.commit();
  • 回滚 connection.rollback();//回滚
上一篇:命名空间“System.Web”中不存在类型或命名空间名称“HttpUtility”。是否缺少程序集引用?


下一篇:数据库连接池与DBUtils工具