Database connection in Magento 2
This tutorial will explain how to get Magento 2 database connection and play with Magento database tables. Actually, Magento 2 gives very handy way to developers in forms object manager. But it has certain rules to use it. You can go to Object Manager Link for more details. Database connection in Magento 2.
So here is the code get database connection in Magento 2
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get(‘Magento\Framework\App\ResourceConnection’);
$connection = $resource->getConnection();
Here $connection veriable has database connection object. Now you can use it insert update or delete rows from table.
$tableName = $resource->getTableName(‘table_name’);
$sql = “Update ” . $tableName . ” Set column_name= ‘”.$coulmn_name.”‘ where entity_id = “.$entityId;
Note: This is an alternative way to get things done in Magento 2. Its always recommended that to use model or create model for custom table in Magento 2