Yii2 如何在没有配置文件的情况下连接到数据库?
How to connect to a database without the config file in Yii2?
对于同样的问题,我正在使用这个问题 中给出的代码。
我意识到 $config
变量不再是 web.php 文件中的变量,它来自 "config" 文件夹,并且他正在 $config
Configuration::setConfig()
函数。
我的问题是我应该写什么
- 在 web.php 文件中的
db
字段(或在 db.php 文件中)到 "create a database connection programmatically without using the config file" ?
- 在函数
Configuration::setConfig()
中正确配置应用程序?
如果我的问题不够清楚,我很抱歉。如果需要,请在评论中询问详细信息。谢谢!
你可以这样定义一个新的连接
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]); and
$db->open();
After the DB connection is established, one can execute SQL statements
like the following eg: :
$command = $db->createCommand('SELECT * FROM post');
$posts = $command->queryAll(); or
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
您可以查看此文档和指南
对于同样的问题,我正在使用这个问题
我意识到 $config
变量不再是 web.php 文件中的变量,它来自 "config" 文件夹,并且他正在 $config
Configuration::setConfig()
函数。
我的问题是我应该写什么
- 在 web.php 文件中的
db
字段(或在 db.php 文件中)到 "create a database connection programmatically without using the config file" ? - 在函数
Configuration::setConfig()
中正确配置应用程序?
如果我的问题不够清楚,我很抱歉。如果需要,请在评论中询问详细信息。谢谢!
你可以这样定义一个新的连接
$db = new yii\db\Connection([ 'dsn' => 'mysql:host=localhost;dbname=example', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]); and $db->open();
After the DB connection is established, one can execute SQL statements like the following eg: :
$command = $db->createCommand('SELECT * FROM post'); $posts = $command->queryAll(); or $command = $connection->createCommand('UPDATE post SET status=1'); $command->execute();
您可以查看此文档和指南