magento 2 connection code example

Example 1: magento 2 get connection

$om = \Magento\Framework\App\ObjectManager::getInstance();
$connectionO = $om->create('Magento\Framework\App\ResourceConnection');
$connection= $connectionO->getConnection();

$sql = 'some query';
$results = $connection->fetchAll($sql);

Example 2: magento 2 db connection

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection('\Magento\Framework\App\ResourceConnection::DEFAULT_CONNECTION'); 
$results = $connection->fetchone($query);

Tags:

Php Example