启动时Databe连接错误

时间:2016-11-21 11:04:05

标签: php database phalcon

我遇到了与数据库连接的问题,特别是当我尝试访问系统并且数据库没有响应时。

我在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;
 }

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

有什么建议吗?

谢谢。

1 个答案:

答案 0 :(得分: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;
    }
        });