Magento2 – Get Database Connection

databasemagento2.2.2table

I wish to have code equivalent in Magento 2.

The below one is Magento 1

$resource = Mage::getSingleton('core/resource'); $connection =
$resource->getConnection('core_read');

I need the above code in Magento 2.

Best Answer

Without a Mage class, how does a developer instantiate model or magento-singleton object? The Mage::getModel and Mage::getSingleton methods have been retired, and in their place Magento has a new “Object Manager” object.

Right now this object manager is a PHP singleton, which you can grab with the following call.

$object_manager = MagentoCoreModelObjectManager::getInstance();

Magento is moving towards an architecture where this object will be automatically available in appropriate places as the _objectManager property.

$this->_objectManager
protected $_resource;
public function __construct(
   ...
   \Magento\Framework\App\ResourceConnection $resource
   ...
   ) {
   $this->_resource = $resource;
}

$connection = $this->_resource->getConnection();

For more information check alanstorm.com