Use multiple / external databases in Drupal 8 By editor, 29 June, 2016 Question How to connect to multiple databases within Drupal 8 ? How to use multiple databases with Drupal 8 ? The database settings (and connection) has 3 levels. 1. KEY 2. TARGET 3. DATA Example: $databases[KEY][TARGET] = array ( DATA ); Like: $databases['default']['default'] = array ( 'database' => 'drupal8_default_db', .... ); Methode 1. Multiple connections Using Different "KEY" (Recommended) 1. Configure your drupal instance for multiple databases (setting.php) 'key' is the first level of the database connection; Example : $databases['default']['default'] = array ( 'database' => 'drupal8_default', 'username' => 'root', 'password' => 'root', 'prefix' => '', 'host' => 'localhost', 'port' => '3306', 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql', ); $databases['myseconddb']['default'] = array ( 'database' => 'mysql', 'username' => 'root', 'password' => 'root', 'prefix' => '', 'host' => 'localhost', 'port' => '3306', 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql', ); 2. Connect to the correct data base: Example: //To get the default database $con = \Drupal\Core\Database\Database::getConnection(); //To get another database (here : 'myseconddb') $con = \Drupal\Core\Database\Database::getConnection('default','myseconddb'); Methode 2. Multiple connections Using Different "TARGETS" (Not recommended, Use for master/slave configuration) 1. Configure your drupal instance for multiple databases (setting.php) 'target' is the second level of the database connection; Example : $databases['default']['default'] = array ( 'database' => 'drupal8_default', 'username' => 'root', 'password' => 'root', 'prefix' => '', 'host' => 'localhost', 'port' => '3306', 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql', ); $databases['default']['myseconddb'] = array ( 'database' => 'mysql', 'username' => 'root', 'password' => 'root', 'prefix' => '', 'host' => 'localhost', 'port' => '3306', 'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql', 'driver' => 'mysql', ); 2. Connect to the correct data base: Example: //To get the default database $con = \Drupal\Core\Database\Database::getConnection(); //To get another database (here : 'myseconddb') $con = \Drupal\Core\Database\Database::getConnection('myseconddb'); And See also How to use database programmatically Database configuration : https://www.drupal.org/docs/7/api/database-api/database-configuration Master / Slave Configuration : https://www.drupal.org/node/1952990 Tags Drupal 8 Code Database Add new comment Database Basic Examples (Select, Merge, Insert ...) Database LIKE condition Database Merge, Insert or Update if exist. Drupal Mysql / Database Data types