Home > PHP Framework > Workerman > body text

What to do if workerman introduces db error

Release: 2019-12-23 10:47:37
Original
2555 people have browsed it

What to do if workerman introduces db error

In order to achieve more efficient server access speed, we will use long connections of mysql or other databases to improve access speed.

The following content uses mysql pdo as an example:

Problem:

When the cli is resident in memory, there will be many situations that cause the created connection to fail;

Solution:

When accessing the database When adding try catch capture

When the error captured is 2006 or 2013, it means that the connection has failed. Reconnect to the database at this time to ensure the normal operation of the program;

// 在和数据库交互的地方加上try catchpublic function Init($query)
    {
        try{
            // todo 这里是操作数据库的逻辑
        }catch (\Exception $e) {
            if ( $e->errorInfo[1] === 2006 || $e->errorInfo[1] === 2013 ) {
                // todo 下面填写 或者调用连接数据库的代码
                $dsn = 'mysql:dbname=' . $this->settings["dbname"] . ';host=' . $this->settings["host"] . '';
                $this->pdo = new \PDO($dsn, $this->settings["user"], $this->settings["password"], array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8;"));

                $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

                $this->pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, true);
                return true;
            }
        }
    }
Copy after login

var_dump($e-> ;errorInfo); The value

array(3) {
  [0]=>
  string(5) "HY000"
  [1]=>
  int(2006)
  [2]=>
  string(26) "MySQL server has gone away"}
Copy after login

For more workerman knowledge, please pay attention to the workerman tutorial column on the PHP Chinese website.

The above is the detailed content of What to do if workerman introduces db error. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!