gpt4 book ai didi

php - 使用 Zend Framework 连接到两个不同的数据库

转载 作者:可可西里 更新时间:2023-10-31 22:09:43 25 4
gpt4 key购买 nike

我这里有一个完全用 Zend FW 编写的中型内部网站。 Intranet 的数据库位于另一台服务器上。现在我需要用一些新功能扩展内部网。为此,我需要连接到同一台服务器(和同一 DBMS)上的另一个数据库。

现在的问题是:最好的方法是什么?我应该创建一个新的 Zend_Config 对象和一个新的 Zend_Db_Adapter 吗?或者我应该使用现有的并尝试使用“使用 otherdbname;”在同一 session 中连接到新数据库的语句?

或者有更好的方法吗?

最佳答案

一种选择是在您的 bootstrap.php 中注册 2 个数据库句柄,每个连接一个。例如:

$parameters = array(
'host' => 'xx.xxx.xxx.xxx',
'username' => 'test',
'password' => 'test',
'dbname' => 'test'
);
try {
$db = Zend_Db::factory('Pdo_Mysql', $parameters);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
} catch (Zend_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
}
Zend_Registry::set('db', $db);

$parameters = array(
'host' => 'xx.xxx.xxx.xxx',
'username' => 'test',
'password' => 'test',
'dbname' => 'test'
);
try {
$db = Zend_Db::factory('Pdo_Mysql', $parameters);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
} catch (Zend_Exception $e) {
echo $e->getMessage();
die('Could not connect to database.');
}
Zend_Registry::set('db2', $db);

在您的 Controller 中(例如):

public function init()
{
$this->db = Zend_Registry::get('db');
$this->db2 = Zend_Registry::get('db2');
}

public function fooAction()
{
$data = $this->db2->fetchAll('select foo from blah');
...
}

关于php - 使用 Zend Framework 连接到两个不同的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1516359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com