Magento 2 Create Database Connection

To get database connection in Magento2, we can use the following code snippet:

Steps:

1) You need to use the below class namespace to include the `ResourceConnection` into your custom class which will provide you various useful methods and those methods can be used for various database related purposes.

Namespace to use in your class: 

use Magento\Framework\App\ResourceConnection;

The above class mainly provides the database connection related public methods as following for global access:
1) getConnection()
2) closeConnection() 
3) getTableName()
4) getTablePrefix()

I mentioned only some of the useful oftenly used methods in regular development.

2) We need to declare following variables to get class object and to hold connection.

protected $_resource;
protected $_connection;

3) We then need to declare the ResourceConnection class in your custom class constructor as following : 
public function __construct(
    ResourceConnection $resource
)
{
    $this->_resource = $resource;        
}
OR
We can skip the step by directly declaring the full class path in constructor as following: 
public function __construct(
    \Magento\Framework\App\ResourceConnection $resource
)
{
    $this->_resource = $resource;        
}
This way now we are ready to get the database connection object.

4) Final step is to declare a general purpose method in your custom class to access the connection object from anywhere you want in your module as following: 
/**
 * @return mixed
 */
public function getDatabaseConnection()
{
    if (!$this->_connection) {
        $this->_connection = $this->_resource->getConnection();
    }
    return $this->_connection;
}
This will always return the object from which you can access the public methods mentioned above in step 1. Hope this is useful for you guys!

 

Leave a Reply