Instantiating a Database Connection Object
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
- 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. - If it is possible, use DI (dependency injection) to use
@databaseservice or$container->get('database');to inject the database connection - If not possible (as in a static method of a class), use
\Drupal::database(). - If services are not yet available,
\Drupal\Core\Database\Database::getConnection()can get a database connection. - 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.
- 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
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion
Still on Drupal 7? Security support for Drupal 7 ended on 5 January 2025. Please visit our Drupal 7 End of Life resources page to review all of your options.