i'm new into the world of Drupal, i'm a student comming from the Symfony ^^

I have create a module an i want to add an database connection for my module. In looking for an answer i have see the method getConnection of the Database class.

I have tried this onto my controller

$connection = \Drupal\Core\Database\Database::getConnection('moduleunicef','password');

for connection at my database called moduleunicef, i have see i need to modif my setting.php file.

/* /sites/default/setting.php*/
$databases['default']['default'] = array(
 'driver' => 'mysql',
 'database' => 'moduleunicef',
 'username' => 'theuser',
 'password' => 'password',
 'host' => 'localhost',
 'prefix' => '',


In result i have this error message (For security i have change the password and user ^^ )

Drupal\Core\Database\ConnectionNotDefinedException: The specified database connection is not defined: root in Drupal\Core\Database\Database::openConnection() (line 366 of core/lib/Drupal/Core/Database/Database.php).

Drupal\Core\Database\Database::getConnection('moduleunicef', 'password') Drupal\unicef42\Controller\PbRouteController->index() call_user_func_array(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber{closure}() call_user_func_array(Object, Array) Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) Stack\StackedHttpKernel->handle(Object, 1, 1) Drupal\Core\DrupalKernel->handle(Object)

So i have tried an over method into my controller

$connection = \Drupal::database();

the test of connection it's Ok but it's the base who i have input onto my setting.php file? or the drupal DataBase created for the install of the website?

I need some namespace onto my controller?


You can do something like this:

    $database_info = array(
        'host' => $host,
        'port' => $port,
        'database' => $dbname,
        'username' => $dbuser,
        'password' => $dbpass,
        'driver' => 'mysql'

// Add connection info
    Database::addConnectionInfo('externaldb', 'default', $database_info);

// Test connection
    try {
        $connection = Database::getConnection('default', 'externaldb');
        $caught     = false;
        return array($caught, $connection);
    catch (PDOException $e) {
        // Ups connection failed
        $connection = NULL;
        form_set_error('syncsae_config_host', t('Connection failed.'));

        $errornumber  = $e->getCode();
        $errormessage = $e->getMessage();

        drupal_set_message(t('Error: @errornum.', array(
            '@errornum' => $errornumber
        )), 'error');
        drupal_set_message(t('Error description: @errormes.', array(
            '@errormes' => $errormessage
        )), 'error');

        $caught = true;
        return array($caught, $connection);

I'm using this one to swith and send a query

in the settings.php add

databases['customer_db']['default'] = [
  'driver' => 'pgsql',
  'database' => 'drupal',
  'username' => 'drupal',
  'password' => 'drupal',
  'host' => 'xx.xx.xx.xx',
  'port' => '5432',
  'prefix' => '',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\pgsql',

Then use when it's necesary

$db = \Drupal\Core\Database\Database::getConnection('default', 'customer_db'); 
$query = $db->query("SELECT * FROM customer");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.