Yii 2 Database DSNs for Each Database Type

Last updated:

Yii2 has changed a few things in comparison to Yii1. One of them is the way you tell Yii what Database Backend you're using. It now uses DSN which are just strings used to specify details to your connection:

return array(
// ...
'components' => array(
    // ...
    'db' => array(
        'class' => 'yii\db\Connection',
        'dsn' => 'INSERT DSN HERE', 
        'username' => 'root',
        'password' => '',
        'charset' => 'utf8',
    ),
),
// ...
);
  • MySQL (TESTED)

    'mysql:host=localhost;dbname=mydatabase'
    
  • SQLite

    'sqlite:/path/to/database/file'
    
  • PostgreSQL

    'pgsql:host=localhost;port=5432;dbname=mydatabase'
    
  • CUBRID

    'cubrid:dbname=demodb;host=localhost;port=33000'
    
  • SQL Server (there's 3 different drivers)

    • sqlsrv driver

      'sqlsrv:Server=localhost;Database=mydatabase'
      
    • dblib driver

      'dblib:host=localhost;dbname=mydatabase'
      
    • mssql driver

      'mssql:host=localhost;dbname=mydatabase'
      
  • Oracle

     'oci:dbname=//localhost:1521/mydatabase'
    

References

Dialogue & Discussion