0

MySQLサーバーに接続して通信するのに役立つPDOクラスを作成しました。私がやろうとしているのは、関数またはメソッドをクラスに追加して、コミットとロールバックとともにMySQLへのトランザクションを開くのに役立つことです。コミットとロールバックを使用したことはありません。

このクラスが呼び出されるたびに自動コミットを何らかの形で停止し、エラーがスローされるたびにロールバックし、このクラス ID が閉じられるたびにコミットすることが、シーンを作ると思います。

私の2つの質問は次のとおりです。1)接続を開いて複数のクエリを実行し、エラーがない場合はコミットすることをお勧めしますか?それ以外の場合はロールバックしてから接続を閉じますか?2)これを既存のクラスに追加するにはどうすればよいですか? は私の現在のPHPクラスです

<?php

class connection {

    private $connString;
    private $userName;
    private $passCode;
    private $server;
    private $pdo;
    private $errorMessage;
    private $pdo_opt = array();
    protected $lastQueryTime;
    protected $lastQuery;
    protected $effectedRows;



    function __construct($dbName = DATABASE_NAME, $serverName = DATABASE_HOST){

        //SET PDO options
        if(TESTING_ENVIRONMENT == 1){
            $this->pdo_opt[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
            $this->pdo_opt[PDO::ATTR_DEFAULT_FETCH_MODE]  = PDO::FETCH_ASSOC;
        }

            $this->pdo_opt[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
            $this->pdo_opt[PDO::SQLSRV_ATTR_ENCODING]  = PDO::SQLSRV_ENCODING_UTF8;

        //sets credentials
        $this->setConnectionCredentials($dbName, $serverName);

        //start the connect
        $this->startConnection();

    }

    function startConnection(){


            $this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);

            if( ! $this->pdo){

                $this->errorMessage  = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
                $this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';
                echo $this->getError();
            }
    }


    //this will close the PDO connection
    public function endConnection(){

        $this->pdo = null;
    }

    //return a dataset with the results
    public function getDataSet($query, $data = NULL)
    {
        $start = microtime(true);
        $cmd = $this->pdo->prepare( $query );

        $cmd->execute($data);
        $this->effectedRows = $cmd->rowCount();
        $ret = $cmd->fetchAll();
        //$cmd->closeCursor();
        $this->lastQueryTime = microtime(true) - $start;
        $this->lastQuery = $query;

        return $ret;
    }



    public function processQuery($query, $data = NULL)
    {
        $start = microtime(true);
               //$this->pdo->beginTransaction();


        $cmd = $this->pdo->prepare( $query );
        $ret = $cmd->execute($data);
               //$this->pdo->commit();
               //$cmd->closeCursor();
        $this->effectedRows = $cmd->rowCount();
        $this->lastQueryTime = microtime(true) - $start;
        $this->lastQuery = $query;

        return $ret;
    }


    //return last insert id
    public function lastInsertId($name = NULL) {
        if(!$this->pdo) {
            return false;
        }

        return $this->pdo->lastInsertId($name);
    }


    //return last insert id
    public function rowCount() {

        return $this->effectedRows;
    }


    public function getOneResult($query, $data = NULL){
        $cmd = $this->pdo->prepare( $query );
        $cmd->execute($data);

        return $cmd->fetchColumn();
    }

    public function getError(){
        if($this->errorMessage != '')
            return $this->errorMessage;
        else
            return true;  //no errors found

    }

    //this where you need to set new server credentials with a new case statment
    function setConnectionCredentials($dbName, $serv){

        switch($serv){

            //the defaults are predefined in the APP_configuration file - DO NOT CHANGE THE DEFAULT
            default:
                $this->connString   = 'mysql:host='.DATABASE_HOST.';dbname='.DATABASE_NAME.';charset=utf8';
                $this->userName     = DATABASE_USERNAME;
                $this->passCode     = DATABASE_PASSWORD;
            break;

            }

    }

public function lastQueryTime() {
    if(!$this->lastQueryTime) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQueryTime;
}

public function lastQuery() {
    if(!$this->lastQuery) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQuery;
}

}

?>

通知を集めた後に編集 されましたが、この方法が必要ですか??

$db = new connection();
$db->beginTransaction(); //begin transaction
$db->processQuery();     //process query #1
$db->processQuery();     //process query #2
$db->commit();           //commit changes
$db->endConnection();    //close connection


public function beginTransaction(){
    $this->pdo->beginTransaction(); 
}

public function commit(){
    $this->pdo->commit(); 
}

public function rollBack(){
    $this->pdo->rollBack(); 
}   

//this will close the PDO connection
public function endConnection(){
    $this->pdo = null;
}
4

1 に答える 1

0

PDO::beginTransaction

/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

PDO::コミット

/* Commit the changes */
$dbh->commit();

この時点で、あなたのconnectionクラスはかなりレベルが低いように感じます。私の推測では、トランザクションをいつ開始し、いつコミットするかをそれ自体で知るのに十分な情報がありません。おそらく、対応するメソッド (rollbackおよびメソッド) を提供し、クラスのユーザーが必要に応じてそれらを呼び出せるようにする必要があります。


あなたの質問に関して、トランザクションはローカルの変更をロールバックするだけではありません。それは原子性についてでもあります。これは、すべて実行されるか、またはまったく実行されない一連の操作です。DB への同時アクセスがあることを忘れないでください。データを操作しているときに、誰かにデータを変更されたくない場合があります。

于 2013-08-01T21:21:00.167 に答える