Yii2: Connection string for different Database Server

  • Avinash
  • 0
  • Dec 07, 2016
  • Web Development

Yii2 supports different database server types and each one have its own way to connect to database. To connect with any database we need to prepare DSN for connection.

In this quick tip we are going to see how DSN should be created for different Database servers.

If you are running basic app of Yii2 then you need to make this changes in db.php file under config directory and in case of advance application it should be done in main.php under config directory.

[ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=reportsa_macromoney', // MySQL, MariaDB //'dsn' => 'sqlite:/path/to/database/file', // SQLite //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle 'username' => 'DB User Name', 'password' => 'Password for selected user', 'charset' => 'utf8', ] ]; ]; ?>
<?php
return [
   'components' =  [
         'db' => [
           'class' => 'yii\db\Connection',
           'dsn' => 'mysql:host=localhost;dbname=reportsa_macromoney', // MySQL, MariaDB
           //'dsn' => 'sqlite:/path/to/database/file', // SQLite
           //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
           //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
           //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
           //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
           //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
           //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
          'username' => 'DB User Name',
          'password' => 'Password for selected user',
          'charset' => 'utf8',
        ]
     ];
];


?>

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: