php PDO mysql问题解决

来源:互联网 发布:越国以鄙远 君知其难也 编辑:程序博客网 时间:2024/05/18 04:14

由于公司需要做一个php的客户端,需要有多线程和数据操作,于是选用tp的DB类加以改用。

问题:

1、测试mysql是否连接正常

private function pdo_ping(){
      try{
        $this->pdo->getAttribute(PDO::ATTR_SERVER_INFO);
      } catch (PDOException $e) {
        $this->connect();
        echo "mysql reconnect success\n\t";
      }
  }

若连接不正常则重新连接

1、事务报错

可能由于已经开启一个数据库事务,在其未提交或撤回期间再开一个事务则报错。

修改代码如下:

  public function beginTransaction(){
        ++$this->transactionLevel;
        if(1==$this->transactionLevel){

            $this->pdo_ping();

            return $this->pdo->beginTransaction();    
        }
    }
    public function commit(){
        return $this->endTransaction(__FUNCTION__);
    }
    public function rollback(){
        return $this->endTransaction(__FUNCTION__);
    }
    private function endTransaction($method){
        $r=true;
        if(1==$this->transactionLevel){
            if(method_exists($this->pdo,$method)){

               $this->pdo_ping();               

               $r=$this->pdo->$method();    
            }
            $this->transactionLevel=0;    
        }else{
            $this->transactionLevel--;
        }
        return $r;    
    }

解释:

若为第一次开始事务 beginTransaction则正常开启,否则不做处理,commit、rollback进行$this->transactionLevel归零做正常处理,否则$this->transactionLevel减一。

2、连接超时

sql语句正确执行query时报错:MySQL server has gone away 是和mysql的连接断开了。

修改代码如下:

   public function query($query)
    {
        $this->pdo_ping();
        $this->queryString = $query;
        try {
            $r=$this->pdo->query($query);    
        } catch (PDOException $e) {
            $this->connect();
            $r=$this->pdo->query($query);
        }
        return $r;
    }

解释:

用try catch 判断$this->pdo->query()是否正常,不正常则重新连接,异常一定要用PDOException获取。

相关连接:

http://blog.csdn.net/jelope/article/details/11964983

http://blog.csdn.net/hello_katty/article/details/45220825

原创粉丝点击