当前位置: 首页>>代码示例>>PHP>>正文


PHP Database::closeConnection方法代码示例

本文整理汇总了PHP中Drupal\Core\Database\Database::closeConnection方法的典型用法代码示例。如果您正苦于以下问题:PHP Database::closeConnection方法的具体用法?PHP Database::closeConnection怎么用?PHP Database::closeConnection使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Drupal\Core\Database\Database的用法示例。


在下文中一共展示了Database::closeConnection方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: testMaxAllowedPacketQueryTruncating

 /**
  * Tests truncation of messages when max_allowed_packet exception occurs.
  */
 function testMaxAllowedPacketQueryTruncating()
 {
     // This test only makes sense if we are running on a MySQL database.
     // Test if we are.
     $database = Database::getConnectionInfo('default');
     if ($database['default']['driver'] == 'mysql') {
         // The max_allowed_packet value is configured per database instance.
         // Retrieve the max_allowed_packet value from the current instance and
         // check if PHP is configured with sufficient allowed memory to be able
         // to generate a query larger than max_allowed_packet.
         $max_allowed_packet = db_query('SELECT @@global.max_allowed_packet')->fetchField();
         if (Environment::checkMemoryLimit($max_allowed_packet + 16 * 1024 * 1024)) {
             $long_name = str_repeat('a', $max_allowed_packet + 1);
             try {
                 db_query('SELECT name FROM {test} WHERE name = :name', array(':name' => $long_name));
                 $this->fail("An exception should be thrown for queries larger than 'max_allowed_packet'");
             } catch (DatabaseException $e) {
                 // Close and re-open the connection. Otherwise we will run into error
                 // 2006 "MySQL server had gone away" afterwards.
                 Database::closeConnection();
                 Database::getConnection();
                 $this->assertEqual($e->getPrevious()->errorInfo[1], 1153, "Got a packet bigger than 'max_allowed_packet' bytes exception thrown.");
                 // Use strlen() to count the bytes exactly, not the unicode chars.
                 $this->assertTrue(strlen($e->getMessage()) <= $max_allowed_packet, "'max_allowed_packet' exception message truncated.");
             }
         } else {
             $this->verbose('The configured max_allowed_packet exceeds the php memory limit. Therefore the test is skipped.');
         }
     } else {
         $this->verbose('The test requires MySQL. Therefore the test is skipped.');
     }
 }
开发者ID:dmyerson,项目名称:d8ecs,代码行数:35,代码来源:LargeQueryTest.php

示例2: connect

  /**
   * {@inheritdoc}
   */
  protected function connect() {
    try {
      // This doesn't actually test the connection.
      db_set_active();
      // Now actually do a check.
      Database::getConnection();
      $this->pass('Drupal can CONNECT to the database ok.');
    }
    catch (\Exception $e) {
      // Attempt to create the database if it is not found.
      if ($e->getCode() == Connection::DATABASE_NOT_FOUND) {
        // Remove the database string from connection info.
        $connection_info = Database::getConnectionInfo();
        $database = $connection_info['default']['database'];
        unset($connection_info['default']['database']);

        // In order to change the Database::$databaseInfo array, need to remove
        // the active connection, then re-add it with the new info.
        Database::removeConnection('default');
        Database::addConnectionInfo('default', 'default', $connection_info['default']);

        try {
          // Now, attempt the connection again; if it's successful, attempt to
          // create the database.
          Database::getConnection()->createDatabase($database);
          Database::closeConnection();

          // Now, restore the database config.
          Database::removeConnection('default');
          $connection_info['default']['database'] = $database;
          Database::addConnectionInfo('default', 'default', $connection_info['default']);

          // Check the database connection.
          Database::getConnection();
          $this->pass('Drupal can CONNECT to the database ok.');
        }
        catch (DatabaseNotFoundException $e) {
          // Still no dice; probably a permission issue. Raise the error to the
          // installer.
          $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage())));
          return FALSE;
        }
        catch (\PDOException $e) {
          // Still no dice; probably a permission issue. Raise the error to the
          // installer.
          $this->fail(t('Database %database not found. The server reports the following message when attempting to create the database: %error.', array('%database' => $database, '%error' => $e->getMessage())));
          return FALSE;
        }
      }
      else {
        // Database connection failed for some other reason than the database
        // not existing.
        $this->fail(t('Failed to connect to your database server. The server reports the following message: %error.<ul><li>Is the database server running?</li><li>Does the database exist, and have you entered the correct database name?</li><li>Have you entered the correct username and password?</li><li>Have you entered the correct database hostname?</li></ul>', array('%error' => $e->getMessage())));
        return FALSE;
      }
    }
    return TRUE;
  }
开发者ID:HamzaBendidane,项目名称:prel,代码行数:61,代码来源:Tasks.php

示例3: testConnectionClosing

 /**
  * Tests the closing of a database connection.
  */
 function testConnectionClosing()
 {
     // Open the default target so we have an object to compare.
     $db1 = Database::getConnection('default', 'default');
     // Try to close the default connection, then open a new one.
     Database::closeConnection('default', 'default');
     $db2 = Database::getConnection('default', 'default');
     // Opening a connection after closing it should yield an object different than the original.
     $this->assertNotIdentical($db1, $db2, 'Opening the default connection after it is closed returns a new object.');
 }
开发者ID:nstielau,项目名称:drops-8,代码行数:13,代码来源:ConnectionTest.php

示例4: testConnectionFailureLogging

 /**
  * Tests logging of connection failures.
  */
 function testConnectionFailureLogging()
 {
     $logger = \Drupal::service('logger.factory');
     // MySQL errors like "1153 - Got a packet bigger than 'max_allowed_packet'
     // bytes" or "1100 - Table 'xyz' was not locked with LOCK TABLES" lead to a
     // database connection unusable for further requests. All further request
     // will result in an "2006 - MySQL server had gone away" error. As a
     // consequence it's impossible to use this connection to log the causing
     // initial error itself. Using Database::closeConnection() we simulate such
     // a corrupted connection. In this case dblog has to establish a different
     // connection by itself to be able to write the log entry.
     Database::closeConnection();
     // Create a log entry.
     $logger->get('php')->error('testConnectionFailureLogging');
     // Re-establish the default database connection.
     Database::getConnection();
     $wid = db_query("SELECT MAX(wid) FROM {watchdog} WHERE message = 'testConnectionFailureLogging'")->fetchField();
     $this->assertTrue($wid, 'Watchdog entry has been stored in database.');
 }
开发者ID:sarahwillem,项目名称:OD8,代码行数:22,代码来源:ConnectionFailureTest.php

示例5: testOpenSelectQueryClose

 /**
  * Tests Database::closeConnection() with a select query.
  */
 function testOpenSelectQueryClose()
 {
     if ($this->skipTest) {
         return;
     }
     // Add and open a new connection.
     $this->addConnection();
     $id = $this->getConnectionID();
     Database::getConnection($this->target, $this->key);
     // Verify that there is a new connection.
     $this->assertConnection($id);
     // Create a table.
     $name = 'foo';
     Database::getConnection($this->target, $this->key)->schema()->createTable($name, array('fields' => array('name' => array('type' => 'varchar', 'length' => 255))));
     // Execute a query.
     Database::getConnection($this->target, $this->key)->select('foo', 'f')->fields('f', array('name'))->execute()->fetchAll();
     // Drop the table.
     Database::getConnection($this->target, $this->key)->schema()->dropTable($name);
     // Close the connection.
     Database::closeConnection($this->target, $this->key);
     // Wait 20ms to give the database engine sufficient time to react.
     usleep(20000);
     // Verify that we are back to the original connection count.
     $this->assertNoConnection($id);
 }
开发者ID:anatalsceo,项目名称:en-classe,代码行数:28,代码来源:ConnectionUnitTest.php

示例6: checkStandardConformingStrings

 /**
  * Ensures standard_conforming_strings setting is 'on'.
  *
  * When standard_conforming_strings setting is 'on' string literals ('...')
  * treat backslashes literally, as specified in the SQL standard. This allows
  * Drupal to convert between bytea, text and varchar columns.
  */
 public function checkStandardConformingStrings()
 {
     $database_connection = Database::getConnection();
     if (!$this->checkStandardConformingStringsSuccess()) {
         // First try to alter the database. If it fails, raise an error telling
         // the user to do it themselves.
         $connection_options = $database_connection->getConnectionOptions();
         // It is safe to include the database name directly here, because this
         // code is only called when a connection to the database is already
         // established, thus the database name is guaranteed to be a correct
         // value.
         $query = "ALTER DATABASE \"" . $connection_options['database'] . "\" SET standard_conforming_strings = 'on';";
         try {
             $database_connection->query($query);
         } catch (\Exception $e) {
             // Ignore possible errors when the user doesn't have the necessary
             // privileges to ALTER the database.
         }
         // Close the database connection so that the configuration parameter
         // is applied to the current connection.
         Database::closeConnection();
         // Recheck, if it fails, finally just rely on the end user to do the
         // right thing.
         if (!$this->checkStandardConformingStringsSuccess()) {
             $replacements = array('%setting' => 'standard_conforming_strings', '%current_value' => 'off', '%needed_value' => 'on', '@query' => $query);
             $this->fail(t("The %setting setting is currently set to '%current_value', but needs to be '%needed_value'. Change this by running the following query: <code>@query</code>", $replacements));
         }
     }
 }
开发者ID:ddrozdik,项目名称:dmaps,代码行数:36,代码来源:Tasks.php


注:本文中的Drupal\Core\Database\Database::closeConnection方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。