Instantiating a Database Connection Object

Last updated on
11 April 2024

This documentation needs work. See "Help improve this page" in the sidebar.

Database interaction should be done via a database connection object. For historical and technical reasons, the type returned by \Drupal::database() is \Drupal\Core\Database\Connection, and this is why it's sometimes called $connection.

In the Procedural code, i.e. *.module*.inc or script files

The best way to instantiate a database connection object is via the Service Container. Example:

$database = \Drupal::database();
// Or
$database = \Drupal::service('database');

This will result in a database connection object that is configured to connect to the default master database as defined in your database configuration in settings.php.

In OOP code

  1. In some cases a database connection object may already be available as a member on the current class; for example, many plugins and services have $this->database (or$this->connection) - the database connection object as a member.
  2. If it is possible, use DI (dependency injection) to use @database service or $container->get('database'); to inject the database connection
  3. If not possible (as in a static method of a class), use \Drupal::database().
  4. If services are not yet available, \Drupal\Core\Database\Database::getConnection() can get a database connection.
  5. In unit tests, we do not have a booted kernel or a built container. Unit tests should generally not access a database. A unit test which needs a database service should be converted to a kernel test.
  6. In kernel and functional test classes we have $this->container->get('database'). Some test authors might discover that the container referenced by the test class will be out of sync with the current container during the request in a functional test. In that circumstance, a test author might call $this->rebuildContainer() and then access $this->container->get('database') again.

Using a different database connection

If your site uses multiple databases, to run a query on a database other than the default one, use Database::getConnection(). For example:

  $connection = \Drupal\Core\Database\Database::getConnection('default', 'other_database');

To set the active connection and return it use the following:

\Drupal\Core\Database\Database::setActiveConnection('other_database');

$database = \Drupal\Core\Database\Database::getConnection();

This will provide a connection to the database defined in settings.php as:

$databases['other_database']['default']

Help improve this page

Page status: Needs work

You can: