Possible timing issues when using setActiveConnection to an external database under normal Drupal 8 operation I'm using Drupal 8.0.5. In my settings.php file I have defined an external database:

$databases['notificationsdb']['default'] = array (
  'database' =&gt; 'NotificationsDB',
  'username' =&gt; 'my_user_name',
  'password' =&gt; 'my_password',
  'prefix' =&gt; '',
  'host' =&gt; '127.0.0.1',
  'port' =&gt; '3306',
  'namespace' =&gt; 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' =&gt; 'mysql',
);


I have then created a custom form where I need values from the NotificationsDB database to populate a form fields. In my custom form class in the __constructor I created an instance of my Notification Client class:

public function __construct() {
        $this-&gt;_notificationClient = new NotificationsClient();
}


In my NotificationsClient class I have the following code:

public function __construct() {
        // Set the active database to notificationsdb
        \Drupal\Core\Database\Database::setActiveConnection('notificationsdb');
        $this-&gt;_db = \Drupal\Core\Database\Database::getConnection();
    }
public function __destruct() {
        // Set the active database back to the default
        \Drupal\Core\Database\Database::setActiveConnection('default');
        // https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Database!Database.php/function/Database%3A%3AsetActiveConnection/8
}


When I go to view my form I get the following error:

Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'notificationsdb.shortcut_set_users' doesn't exist: SELECT ssu.set_name AS set_name FROM {shortcut_set_users} ssu WHERE (ssu.uid = :db_condition_placeholder_0); Array ( [:db_condition_placeholder_0] => 1 ) in Drupal\shortcut\ShortcutSetStorage->getAssignedToUser() (line 103 of core/modules/shortcut/src/ShortcutSetStorage.php).

From what I can tell the Shortcuts module is trying to run some queries against the NotificationsDB. I'm guessing this is a timing issue. I'm also concerned with how Drupal handles multiple database connections.
In looking at the getConnections method closer you can pass it the $target and $key parameters directly and it will return a handle to the specified database.

$this-&gt;_db = \Drupal\Core\Database\Database::getConnection('default', 'notificationsdb');


This way you don't have to mess around with setting the active database.