Yii2 创建数据库连接

Yii2 Create Database Connection(Yii2 创建数据库连接)
本文介绍了Yii2 创建数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用配置文件的情况下以编程方式创建数据库连接.我有一个表单,其中用户输入数据库详细信息,例如 hostnameusernamepassworddatabase name.根据这些细节,建立一个新的测试连接,如果通过,它应该生成必要的文件.这是我尝试过的:

I want to create a database connection programmatically without using the config file. I have a form wherein the user enters the database details like the hostname, username, password and the database name. On the basis of these details a new test connection is made and if it passes it should generate the necessary files. This is what I have tried:

// Create Test DB Connection
Yii::$app->set('id', [
                    'class'    => 'yiidbConnection',
                    'dsn'      => $dsn,
                    'username' => $form->username,
                    'password' => $form->password,
                    'charset'  => 'utf8'
                ]);
try {
    // Check DB Connection
    if (Yii::$app->db->getIsActive()) {
       // Write Config
        $config['components']['db']['class']    = 'yiidbConnection';
        $config['components']['db']['dsn']      = $dsn;
        $config['components']['db']['username'] = $username;
        $config['components']['db']['password'] = $password;
        $config['components']['db']['charset']  = 'utf8';

        Configuration::setConfig($config);
        $success = TRUE;
        return $this->redirect(['init']);
    }else{
        $errorMsg = 'Incorrect Configurations';
    }
} catch (Exception $e) {
        $errorMsg = $e->getMessage();
}

我一次又一次地对此进行了测试,即使配置正确,它也会出现错误.感谢所有的帮助.提前致谢!

I have tested this again and again and even with correct configurations it is giving an error. All the help is appreciated. Thanks in advance!

推荐答案

我意识到了我的错误.当使用 Yii::$app->set() 来设置 db 连接时,你甚至必须手动 open 使用Yii::$app->db->open().Yii 不会为您打开连接.

I realised my mistake. When using Yii::$app->set() for setting up the db connection, you have to even manually open the connection using Yii::$app->db->open(). Yii doesn't open up the connection for you.

这篇关于Yii2 创建数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)