8 Database.php final public static Database::getConnection($target = 'default', $key = NULL)
7 database.inc final public static Database::getConnection($target = 'default', $key = NULL)

Gets the connection object for the specified database key and target.


$target: The database target name.

$key: The database connection key. Defaults to NULL which means the active key.

Return value

DatabaseConnection The corresponding connection object.

71 calls to Database::getConnection()
ConnectionUnitTest::getConnectionID in modules/simpletest/tests/database_test.test
Returns the connection ID of the current test connection.
ConnectionUnitTest::setUp in modules/simpletest/tests/database_test.test
Sets up unit test environment.
ConnectionUnitTest::testOpenClose in modules/simpletest/tests/database_test.test
Tests Database::closeConnection() without query.
ConnectionUnitTest::testOpenQueryClose in modules/simpletest/tests/database_test.test
Tests Database::closeConnection() with a query.
ConnectionUnitTest::testOpenQueryPrefetchClose in modules/simpletest/tests/database_test.test
Tests Database::closeConnection() with a query and custom prefetch method.

... See full list


includes/database/database.inc, line 1463
Core systems for the database layer.


Primary front-controller for the database system.


final public static function getConnection($target = 'default', $key = NULL) {
  if (!isset($key)) {
    // By default, we want the active connection, set in setActiveConnection.
    $key = self::$activeKey;
  // If the requested target does not exist, or if it is ignored, we fall back
  // to the default target. The target is typically either "default" or
  // "slave", indicating to use a slave SQL server if one is available. If
  // it's not available, then the default/master server is the correct server
  // to use.
  if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
    $target = 'default';

  if (!isset(self::$connections[$key][$target])) {
    // If necessary, a new connection is opened.
    self::$connections[$key][$target] = self::openConnection($key, $target);
  return self::$connections[$key][$target];


Note that order of key/target is reversed from Database::addConnectionInfo.

This retrieves an existing connection, rather than creating a new one. You should not ->destroy() your connection in a naïve attempt to clean up after yourself, if you don't want to cause a White Screen of Death that generates no error messages whatsoever.