Score:-1

How do I programmatically set a database connection?

cn flag

Hello can anybody help with a external Database Connection.

$postgis_database = array(
        'database' => $drugis_postgis_connection->getdatabase(),
        'username' => $drugis_postgis_connection->getusername(),
        'password' => $drugis_postgis_connection->getpassword(),
        'host' => $drugis_postgis_connection->gethost(),
        'driver' => 'pgsql',

    );
    Database::setActiveConnection('postgis','default', $postgis_database);
    \Drupal::database();
    $info = Database::getConnection();
    dpm($info);

$info is the default connection, i don't know how to connect to 'postgis' connection

Kevin avatar
in flag
Why isn't this a part of the databases array in settings.PHP? What is the error?
Steffen  avatar
cn flag
There is no error. getConnectionInfo(); show me the default database. This is part of config entity connection modul for multiple database connections. I can't switch to 'postgis'
ru flag
There is no [setActiveConnection](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Database.php/function/Database%3A%3AsetActiveConnection/9.0.x) with more than one parameter. Take a look at [Database::addConnectionInfo](https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Database%21Database.php/function/Database%3A%3AaddConnectionInfo/9.0.x). You really should try to get a proper IDE with code completition up and running (like VS Code or PHPStorm), you don't have to blindly guess function parameters, an IDE will answer questions like these on the fly.
Jaypan avatar
de flag
You can declare multiple database connections in settings.php, and switch between then https://www.drupal.org/docs/drupal-apis/database-api/instantiating-a-database-connection-object#s-using-a-different-database-connection
Score:0
us flag

Database::setActiveConnection() just sets as active connection a connection defined in the settings.php file, or added from a previous call to Database::addConnectionInfo().

The correct code would be the following one.

$postgis_database = [
  'database' => $drugis_postgis_connection->getdatabase(),
  'username' => $drugis_postgis_connection->getusername(),
  'password' => $drugis_postgis_connection->getpassword(),
  'host' => $drugis_postgis_connection->gethost(),
  'driver' => 'pgsql',
];

//                          $key      $target
Database::addConnectionInfo('postgis','default', $postgis_database);
//                            $target    $key
Database::setActiveConnection('default', 'postgis');

Notice the parameters order in the last two method calls. Notice also the array index order used in the $database array set in the settings.php file.

//         $key       $target
$databases['default']['default'] = [
  'database' => 'databasename',
  'username' => 'sqlusername',
  'password' => 'sqlpassword',
  'host' => 'localhost',
  'port' => '3306',
  'driver' => 'mysql',
  'prefix' => '',
  'collation' => 'utf8mb4_general_ci',
 ];

The connections added with Database::addConnectionInfo() aren't permanent; they are added to the static property of the Database class. All the functions/methods that want to use the connection defined in $postgis_database needs to execute the code I showed before querying the database or saving values in the database.
It's probably better to add the extra connections in the settings.

An error to avoid is calling Drupal functions that query a specific Drupal database table after calling Database::setActiveConnection('default', 'postgis'). For example, calling taxonomy_term_load_multiple_by_name() after Database::setActiveConnection('default', 'postgis') won't work, except in the case the postgis/default database contains a copy of the tables used from Drupal. (Usually, that isn't the case, as a module using a different database isn't going to make a copy of the tables Drupal expects to find, in that database.)
Before calling functions like taxonomy_term_load_multiple_by_name(), the code should call Database::setActiveConnection(), which restores the active connection to the default one used by Drupal, which is for a database containing all the tables used from Drupal.

Steffen  avatar
cn flag
Thank you very much I forget to copy the addConnectionInfo method in here and wrote instead of this the parameter in setActiveConnection(). But know with the key and the target in setActiveConnection it work. Thanks
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.