Define the secondary Database in your "settings.php",
Switch to the Database inside of your module,
Query that database,
Swap back to the default Database when finished.
Detailed example
The following is an example of changing between the default Drupal database and a second, additional, database in a custom module, to query the second one.
1. Define the secondary Database in your "settings.php" The file, https://api.drupal.org/api/drupal/sites%21default%21default.settings.php/10 , under the "View Source" section, defines the format for the $databases variable. Essentially, the first key is the database name and the second key is used as a replication database name, or a "target" name, if you wish to use primary/replica database replication for your site.
$databases['database_name']['database_target']
If you are wanting to access a different database, in addition to your Drupal database, then use the first key name for the $databases variable.
For example, the following code snippet defines the configurations for the default Drupal database and an additional database, named "second_db". Note the keys used for the $databases variable.
2. Switch to the Database inside of your module Switch to the additional database by using the Database::setActiveConnection() and Database::getConnection() static methods. For the example presented here, this would be a call such as:
// Change the active connection to the additional database
Database::setActiveConnection('second');
// Get the database connection for the additional database
$second_db_conn = Database::getConnection();
3. Query the database Perform the query to the database that is not the default Drupal database.
// Execute a query on tables in the additional database
$result = $second_db_conn->select('some_table', 't')
->fields('t', ['id', 'column_name'])
->range(0, 1)
->execute()
->fetchAll();
// Do something with the result
// ...
4. Swap back to the default Database when finished Change the connection back to the default Drupal database connection.
// Switch back to the default Drupal database.
Database::setActiveConnection();
That's it, you have successfully implemented a change between your default Drupal database and an additional one!