如何动态更改数据库连接
问题描述:
我使用两个数据库作为我的项目。在配置中。 yml文件如何动态更改数据库连接
all:
master:
class: sfDoctrineDatabase
param:
dsn: 'mysql:host=localhost;dbname=livetloc'
username: root
password: console
client:
class: sfDoctrineDatabase
param:
dsn: 'mysql:host=localhost;dbname=testloc'
username: root
password: console
然后我生成模式和模型。现在我需要动态更改数据库连接。如果我在我的项目中编写新代码,我需要在testloc数据库上测试它。之后,我会将其更改为liveloc db。该项目由四名成员使用。我将新功能添加到它,四个成员同时使用该项目,但我使用“testloc”db。其他人正在使用“Liveloc”分贝。在单个环境中更改特定登录特定用户的数据库的解决方案是什么?
答
我曾在以前的项目需要,这是我如何解决它:
在你的控制器:
// we get the params in your databases.yml file for your data source "client"
$dbParams = sfContext::getInstance()->getDatabaseManager()->getDatabase('client');
$paramsArray = array(
$dbParams->getParameter('dsn'),
$dbParams->getParameter('username'),
$dbParams->getParameter('password'),
'testloc'
);
// setting "false" avoids this new connection to replace your default one
$newConnection = Doctrine_Manager::getInstance()->openConnection($params, 'name_of_connection', false);
$query = "SELECT * FROM table";
$result = $newConnection->fetchAll($query);
,因为它使用symfony的背景下,是不是很爽,但该做的伎俩)。在测试环境中,我认为这很好。