Mysql
 sql >> Datenbank >  >> RDS >> Mysql

So verwenden Sie MySQL-Transaktionen richtig

Am besten emulieren Sie verschachtelte Transaktionen. Schreiben Sie dazu einen Wrapper für Ihren Datenbankzugriff (Pseudocode)

class MyMysqli {
    protected $realDb;
    protected $transaction_count =0;

    public function __construct ($host, $username , $passwd, $dbname){
        $this->realDb = new Mysqli($host, $username, $passwd, $dbname);
    }
    public function __get($property){
        return $this->realDb->$property;
    }

    public function __set($property, $value){
        return $this->realDb->$property = $value;
    }

    public function __call($method, $args){
        return call_user_func_array(array($this->realDb, $method), $args);
    }

    // overload begin_transaction, commit and rollback
    public function begin_transaction(){
         $this->transaction_count++;
         if ($this->transaction_count == 1){
               $this->realDb->begin_transaction();
         }
    }
    public function commit(){
         $this->transaction_count--;
         if($this->transaction_count == 0){
              $this->realDb->commit();
         }
    }

    public function rollback(){
         throw new Exception("Error");
    }