Multiple databases can be connected to Drupal using the Database API and configuring settings.php file.
Use the Database API to connect to additional databases
Add the database connection details to settings.php file
Use the db_set_active() function to switch between databases
Use the db_query() function to execute queries on the selected database
#Drupal 8
#Adding additional databases to your configuration
Preferably you would add your configuration to the settings.php file for your site so that all modules can interact with the new database.
In your settings.php:
$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['second']['default'] = array (
'database' => 'drupal8_second',
'username' => 'root',
'password' => 'root',
'prefix' => '',
'host' => 'localhost',
'port' => '3306',
'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
'driver' => 'mysql',
);
#Connect to the correct data base:
//To get the default database key "default"
$con = \Drupal\Core\Database\Database::getConnection();
//To get another database (here : 'second')
$con = \Drupal\Core\Database\Database::getConnection('default','second');
//To set the active connection
$conn = \Drupal\Core\Database\Database::setActiveConnection('second');