I recently saw a very helpful post about how to connect to an external database from a Craft plugin and I wanted to confirm I understood the implementation correctly.
On this response the author recommended a way to leverage Yii's Query Builder on external databases. Is the following snippet the way to properly implement this in a service? Do I need to manually "close" this connection or is this alone the way to implement this?
<?php
// Connect to an external database
$db = Craft::createComponent([
'emulatePrepare' => true,
'charset' => 'utf8',
'class' => 'Craft\DbConnection',
'autoConnect' => true,
]);
$db->connectionString = 'mysql:host=localhost;dbname=MY_DB;port=3306';
$db->username = 'UN';
$db->password = 'PW';
// Use Query Builder to fetch data from the database
$data = $db->createCommand()
->select("*")
->from("TBL")
->queryAll();
// Pass along the data to be used in a template via variables
return $data;