本文介绍了Yii2 在运行时设置数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
在我的 Yii2(基本应用程序)web.php 中,我将 NULL db 连接配置为第二个数据库连接.
In my Yii2 (basic application) web.php I configure a NULL db connection as 2nd database connection.
这需要填充来自主数据库连接记录的有效参数:
This needs to be filled with valid parameters which are coming from a record on the main db connection:
'db' => require(__DIR__ . '/db.php'),
'db2' => [
'class' => 'yiidbConnection',
'dsn' => NULL,
'username' => NULL,
'password' => NULL,
'charset' => 'utf8',
],
初始化 app() 后,我需要使用从另一个数据库中检索到的值填写 NULL 参数,以便在模型中进一步使用它.
After initializing the app() i need to fill out the NULL parameters with values that i retrieve from another database to further use it in models.
我如何在 Yii2 中实现这一点?
How can i achieve this in Yii2?
推荐答案
没问题,支持
Yii::$app->db2->close(); // make sure it clean
Yii::$app->db2->dsn= 'yourdsn';
Yii::$app->db2->username = 'username';
Yii::$app->db2->password = 'password';
完成,现在可以使用了
Yii::$app->db2->...
另一种方式:
$connection = new yiidbConnection([
'dsn' => $dsn,
'username' => $username,
'password' => $password,
]);
$connection->open();
$command = $connection->createCommand('SELECT * FROM post')->....;
参考:http://www.yiiframework.com/doc-2.0/yii-db-connection.html
这篇关于Yii2 在运行时设置数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)