【问题标题】:Databe connection error on start启动时数据库连接错误
【发布时间】:2017-04-04 18:07:33
【问题描述】:

我在连接数据库时遇到问题,特别是当我尝试访问系统但数据库没有响应时。

我的 services.php 文件中出现错误。

这是代码:

     try{
$di->set('db', function () use ($config) {
    $config = $config->get('database')->toArray();
    $dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
    if (stripos($config['adapter'], 'Mysql')!== false) {
        $mi_conf = array(
            "host" => $config['host'],
            "username" => $config['username'],
            "password" => $config['password'],
            "dbname" => $config['dbname'],
            "options" => array(
                PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
            )
        );      
    } else {
        $mi_conf = array(
            "dbname" => '//'.$config['host'].'/'.$config['dbname'],
            "username" => $config['username'],
            "password" => $config['password'],
            'charset' => 'utf8'
        );
    }

    unset($config['adapter']);

    return new $dbClass($mi_conf);
});
 } catch (Exception $e) {
     $error .= 'db, ';
     return null;
 }

我不知道是否有必要在此处进行更改,或者我必须对每个模型的每个调用进行更改。

有什么建议吗?

谢谢。

【问题讨论】:

  • 您遇到的错误是什么?
  • 连接超时。数据库处于脱机状态,我再次打开,但是,我想捕捉这个错误。谢谢。

标签: php database phalcon


【解决方案1】:

代码看起来没有错误。 使用setShared避免多次连接数据库,或者使用配置上的“persistent”属性生效。也许它可以解决问题。顺便把try catch改成服务创建的那一刻,这样就可以捕获异常了。

        $di->setShared('db', function () use ($config) {
try {
            $config  = $config->get('database')->toArray();
            $dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
            if (stripos($config['adapter'], 'Mysql') !== false) {
                $mi_conf = array(
                    "host"     => $config['host'],
                    "username" => $config['username'],
                    "password" => $config['password'],
                    "dbname"   => $config['dbname'],
                    "persistent" => false,
                    "options"  => array(
                        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
                    ),
                );
            } else {
                $mi_conf = array(
                    "dbname"   => '//' . $config['host'] . '/' . $config['dbname'],
                    "username" => $config['username'],
                    "password" => $config['password'],
                    "persistent" => false,
                    'charset'  => 'utf8',
                );
            }

            unset($config['adapter']);

            return new $dbClass($mi_conf);
} catch (Exception $e) {
        $error .= 'db, ';
        return null;
    }
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 1970-01-01
    • 2020-01-30
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    相关资源
    最近更新 更多