数据库
首页 > 数据库> > php – 如何检查Zend_Db_Adapter_Pdo_Mysql对象是否连接到数据库

php – 如何检查Zend_Db_Adapter_Pdo_Mysql对象是否连接到数据库

作者:互联网

我正在开发一个Zend应用程序,我需要保留数据库对象的单个实例,并在当前实例以某种方式断开连接时重新连接.这是代码:

class Resource_PdoMysql extends Zend_Application_Resource_ResourceAbstract
{
    const KEY = 'PDO_MYSQL';

   private static function connect()
   {
        $connParams = array("host" => host,
        "port" => 'port',
        "username" => 'username',
        "password" => 'password',
        "dbname" => 'dbname');
        $db = new Zend_Db_Adapter_Pdo_Mysql($connParams);
        return $db;
    }
    public static function getConnection()
    {
         if (!Zend_Registry::isRegistered(self::KEY)) 
         {
               $db = self::connect();
               Zend_Registry::set(self::KEY, $db);
         }

         return Zend_Registry::get(self::KEY);  
    }

    public static function reconnect()
    {
        $db = self::connect();
        Zend_Registry::set(self::KEY, $db);
    }

    public function init()
    {
        return self::getConnection();
    }

}

Am using $db like this
$db = Resource_PdoMysql::getConnection();
// <Here I need to check if the connection is open before proceeding>
$db->insert('table', $data);

解决方法:

根据Zend_Db_Adapter documentation,您可能在调用适配器getConnection()方法后捕获异常.这是示例中的复制粘贴摘录:

try {
    $db = Zend_Db::factory('Pdo_Mysql', $parameters);
    $db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
    // perhaps a failed login credential, or perhaps the RDBMS is not running
} catch (Zend_Exception $e) {
    // perhaps factory() failed to load the specified Adapter class
}

希望有所帮助,

标签:zend-db,php,zend-framework,database-connection
来源: https://codeday.me/bug/20190902/1793227.html