1

I created a module and I want to add a database connection for my module. In looking for an answer, I noticed the getConnection() method of the Database class.

I tried this code in a controller.

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

I added the following code in the setting.php file.

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'moduleunicef',
  'username' => 'theuser',
  'password' => 'password',
  'host' => 'localhost',
  'prefix' => '',
);

I get the following error message.

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)

I tried the following code and it works.

$connection = \Drupal::database();

What parameters do I need to pass to Database::getConnection()?

2
1

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);
    }
1

I'm using this code to change connection and query a database table.

In the settings.php file, add the following code.

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',
];

To query the database, use the following code.

$db = \Drupal\Core\Database\Database::getConnection('default', 'customer_db'); 
print_r($db->databaseType());
$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.