zoukankan      html  css  js  c++  java
  • mysql的事务处理

    看一个实际情况

    有一张银行账号表

    create table account 

    (id int primary key,

    balance float);

    现在有一段php程序要完成 把 1号 10 元钱,转到 2号账号上

    <?php
        $mysqli=new MySQLi("localhost","root","hsp123","test");
        if($mysqli->connect_error){
            die($mysqli->connect_error);
        }
        $sql1="update account set balance=balance-2 where id=1";
        $sql2="update account2 set balance=balance+2 where id=2";
        $b1=$mysqli->query($sql1) or die($mysqli->error);
        $b2=$mysqli->query($sql2) or die($mysqli->error);
        if(!$b1||!$b2){
            echo "失败";
        }else{
            echo "成功";
        }
        $mysqli->close();
    ?>

    这时,我们需要有一种方法来控制两句sql语句同时成功,同时失败.

    ->事务 

    事务

    基本:事务用于保证数据的一致性,它由一组相关的dml语句组成,该组的dml语句要么全部成功,要么全部失败。如:网上转账就是典型的要用事务来处理,用以保证数据的一致性

    现在我们使用事务来完成上面的代码

    <?php
    
        $mysqli=new MySQLi("localhost","root","hsp123","test");
        if($mysqli->connect_error){
            die($mysqli->connect_error);
        }
        
        //将提交设为false[事务一旦提交就没有机会回滚.]
        $mysqli->autocommit(false);
        //-> savepoint a;会把但前情况记录
        $sql1="update account set balance=balance-2 where id=1";
        $sql2="update account2 set balance=balance+2 where id=2";
    
        $b1=$mysqli->query($sql1) ;
        $b2=$mysqli->query($sql2) ;
    
        if(!$b1||!$b2){
            echo "失败,回滚".$mysqli->error;
            //回滚!
            $mysqli->rollback();
        }else{
            //提交 [一旦提交没有机会回滚]
            $mysqli->commit();
        }
        $mysqli->close();
        //显示控制台
    ?>    

    ☞ 在mysql控制台可以使用事务来操作,具体步骤如下

    1. 开启一个事务

    start transaction

    1. 做保存点

    savepoint 保存点名称

    1. 操作....
    2. 可以回滚,可以提交

    4.1 如果没有问题提交

    commit

    4.2 如果你觉得有问题,就回滚

    rollback to 保存点.

    u 事务的acid特性

    原子性,一致性,持久性,隔离性.

  • 相关阅读:
    [日本语]自动词和他动词区别的重要性
    [日本语]授受关系动词总结
    [日本语]至少すくなく(と)も
    python3: 文件与IO
    python3: 迭代器与生成器(1)
    python3: 数字日期和时间(2)
    python3: 数字日期和时间(1)
    python3: 字符串和文本(4)
    Python Frame
    python3: 字符串和文本(3)
  • 原文地址:https://www.cnblogs.com/xs-yqz/p/5137786.html
Copyright © 2011-2022 走看看