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

如何在自定义模块Drupal8中在运行时连接外部数据库,drupal,Drupal,我是drupal8开发人员。我想连接到模块中的其他外部数据库。类似地,在D7中也是这样: $other_database = array( 'database' => 'databasename', 'username' => 'username', // assuming this is necessary 'password' => 'password', // assuming this is necessary 'host

我是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中尝试了这个,但它抛出了一个错误。在这方面你能帮我吗?

你可以像这样在drupal 8中使用db\u set\u sctive方法


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

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

    $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();
$database=array(
'数据库'=>,
“用户名”=>,
“密码”=>,
“主机”=>,
“驱动程序”=>“mysql”,
“端口”=>“3306”,
'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql'
);
\Drupal\Core\Database\Database::addConnectionInfo(“”,'default',$Database);
db_设置_激活(“”);
drupal_flush_all_缓存();