Drupal Database Getting Started

Database: Getting Started

  • Introduction

    • Configuration
    • Read & Write Connections
    • Using Multiple Database Connections
  • Running Raw SQL Queries

    • Listening For Query Events
  • Database Transactions

Drupal makes interacting with databases extremely simple across a variety of database backends using either raw SQL, the Database API, and the Entity API. Currently Drupal supports five databases:

  • MySQL / MariaDB (recommended)
  • PostgreSQL
  • SQLite
  • SQL Server
  • Mongodb (community add-on)

Configuration

The database configuration for your application is located at /web/sites/default/settings.php.  In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for most of the supported database systems are provided in this file.

Using Multiple Database Connections

When using multiple connections, you may access each connection via the connection object. The name passed to the connection method should correspond to one of the connections listed in your /web/sites/default/settings.php configuration file:

 $result = $connection->query("SELECT id, example FROM {mytable}", [], [ 'target' => 'slave', 'fetch' => PDO::FETCH_ASSOC, ]);

Creating a database object:

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

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

Please note that the Database API may not always be the best option for interacting with data. API use in Drupal is usually situational, e.g. using the Entity API for CRUD operations, rather than the Database API directly.

Running Raw SQL Queries

Once you have configured your database connection, you may run queries using the connection object. The connection object provides methods for each type of query: select, update, insert, delete, and statement.

Running A Select Query

To run a basic query, you may use the select method on the connection object:

 $result = $connection->query("SELECT example FROM {mytable} WHERE id = :id", [ ':id' => 1234, ]);

The word "Drupal" and the wordmark logo are registered trademarks of Dries Buytaert.