Using an Additional Database in Drupal 7

Posted 16th August 2011

One of the nice, lesser-​known fea­tures of Dru­pal 7 is the abil­ity to use addi­tional data­bases and switch at ease. This might be use­ful for exter­nal data­bases, or if you have another data­base in an alter­na­tive for­mat — per­haps you have an SQLite data­base that for per­for­mance rea­sons, you don’t wish to migrate. (Yes, Dru­pal 7 now sup­ports SQLite!) The con­fig­u­ra­tion can be a lit­tle con­fus­ing at first, so let’s look at a settings.php file set up to use two data­bases: drupal on Localhost, and db2 sit­u­ated at db.example.com.

$databases = array (
  'default' => 
  array (
    'default' => 
    array (
      'database' => 'drupal',
      'username' => 'username',
      'password' => 'password',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'external' => 
  array (
    'default' => 
    array (
      'database' => 'db1',
      'username' => 'username2',
      'password' => 'password2',
      'host' => 'db.example.com',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);