简体   繁体   English

如何以最简单的方式处理mysql连接异常

[英]How to handle mysql connection exception in the simplest way

I am trying to figure out how to handle the mysql connection within a class. 我试图弄清楚如何处理一个类中的mysql连接。 Without always wrapping it in an if statement. 不必总是将其包装在if语句中。 Here is an example to help you understand what i am trying to do. 这是一个示例,可以帮助您了解我要执行的操作。

    class Database {
      protected $conn;
      protected $password;
      protected $username;
      protected $servername;

      public function Database(){
       $this->conn = new mysqli($this->servername,$this->username,$this->password);
      }

      public function scriptA(){
       if ($this->conn->connect_error) {
           die("Connection failed: " . $conn->connect_error);
        } else{
        //do script A
           return $result;
        }
     }

     public function scriptB(){
      if ($conn->connect_error) {
          die("Connection failed: " . $conn->connect_error);
      } else{
        //do script B
       return $result;
      }
    }

} }

As you can see if i were to add more scripts i would have to add in a lot of if catches to check it has been connected. 如您所见,如果我要添加更多脚本,则必须添加很多if捕获来检查它是否已连接。 is there something like a function exception handler that php has? 是否有类似php的函数异常处理程序? IE function foo throws exception? IE函数foo引发异常?

Here is a Simple way to handle exceptions using PDO : 这是使用PDO处理异常的简单方法:

    class Connection{
            public    $db;
            protected $DB_HOST;
            protected $DB_NAME;
            protected $DB_USER;
            protected $DB_PASSWORD;

            function __construct($db_host,$db_name,$db_user,$db_password){
                try{
                    $this->DB_HOST = $db_host;
                    $this->DB_NAME = $db_name;
                    $this->DB_USER = $db_user;
                    $this->DB_PASSWORD = $db_password;


                    $this->db = new pdo('mysql:host='.$this->DB_HOST.';dbname='.$this->DB_NAME,$this->DB_USER,$this->DB_PASSWORD);                      
                }catch(PDOException $e){
                    die($e->getMessage());
                }
            }   

    }

$con = new Connection('db_host','db_name','db_user','db_password');

// display something else here in case connection succeded.
echo 'congratulation you are no connected to your database !';
  1. It's a bad idea to use die() inside a class method. 在类方法中使用die()是个坏主意 Your application might stop unexpectedly with partial output sent, errors not handled correctly etc. It's like you switch of electricity on the server while the script is running. 您的应用程序可能会因发送部分输出而意外停止,错误无法正确处理等。这就像您在脚本运行时在服务器上接通了电一样。 The result is unpredictable. 结果是不可预测的。 A small note here, you will have hard times testing the code with unit tests when you have die() statements. 这里需要注意的一点是,当您拥有die()语句时,将很难用单元测试来测试代码。 I can list more issues here if you will. 如果您愿意,我可以在这里列出更多问题。

  2. PDO throws exceptions when something goes wrong. 发生错误时,PDO会引发异常 But most likely you do not need to catch the exception in Connection class because you can not handle the exception in this class. 但是很可能您不需要在Connection类中捕获异常,因为您不能在此类中处理异常。 You can not sent error to the customer or log the error or rollback some activity in progress or notify administrator etc. You can not do anything except may be through a different exception. 您不能将错误发送给客户,也不能记录错误或回滚正在进行的活动或通知管理员等。您可能无法做任何事情,除非可能是由于其他异常。

  3. I think you need to review your application and catch PDOException in the code where you can really do something. 我认为您需要检查您的应用程序,并在代码中捕获PDOException ,您才能真正做到这一点。 Most likely this is done by your framework and you need to alter the framework's default behavior. 这很可能是由您的框架完成的,您需要更改框架的默认行为。 Another option is to do this in the class which is responsible for some business logic. 另一个选择是在负责某些业务逻辑的类中执行此操作。 In this case you might do something different if SQL fails. 在这种情况下,如果SQL失败,您可能会做一些不同的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM