如何在自定义模块drupal 8中运行时连接外部数据库

时间:2016-04-03 13:45:28

标签: drupal

我是drupal8开发人员。我想连接到模块中的其他外部数据库。同样在D7中,它是这样的:

$other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

我在D8中尝试了这个,但是它引发了一个错误。你能帮我这方面吗?

2 个答案:

答案 0 :(得分:0)

你可以在drupal 8中使用db_set_sctive方法,就像这样

\Drupal::Database->setActiveConnection($key)

答案 1 :(得分:0)

连接到外部数据库后,您应该实用地清除缓存。 下面是代码片段:

    $database = array(
          'database' => <your_database_name>,
          'username' => <your_username>, 
          'password' => <your_password>, 
          'host' => <host>,
          'driver' => 'mysql',
          'port'    => '3306',
          'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql'
      );
    \Drupal\Core\Database\Database::addConnectionInfo('<your_key>', 'default', $database);
    db_set_active('<your_key>');

    drupal_flush_all_caches();