[SQL DB]A small change supports multiple transactions

mason X

New Member
May 8, 2019
26
2
3
28
Thanks for the contribution of webengine
To this end, I contributed a data multiple transaction processing


class.database.php Join at the footer
PHP:
/**
* 事务启动
*/
public function beginTransaction(){
    #开启异常处理
    $this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    #开始一个事务,关闭自动提交
    $this->db->beginTransaction();

}

/**
* query
* @param $sql
* @param string $array
*/
public function exec($sql, $array=''){
    if(!is_array($array)) $array = [$array];
    $query = $this->db->prepare($sql);
    if (!$query) { #错误
        $this->error = $this->trow_error();
        $query->closeCursor();

    } else {   #正确
        if($query->execute($array)) {
            $query->closeCursor();
        } else {
            $this->error = $this->trow_error($query);
        }
    }
}
/**
* 自动完成
*/
public function commit()
{
    $this->db->commit();
}

/**
* 回滚
*/
public function rollBack(){

    $this->db->rollBack();
}
We use the following code to test!
^^Everything will be better

PHP:
# Test transaction

try {
    $MU = Connection::Database('MuOnline');
    $MU->beginTransaction();
    $MU->exec("UPDATE [MARKET] SET [price] = '5555' WHERE ID > 30");
    $MU->exec("UPDATE [MARKET] SET [price] = '3333' WHERE ID < 30");
    $MU->commit();

} catch (Exception $e) {
    $MU->rollBack();
    echo "Failed: " . $e->getMessage();
}
 
Last edited: