Database connection in Magento 2

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

[php]</pre>
$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get(‘Magento\Framework\App\ResourceConnection’);
$connection = $resource->getConnection();
[/php]

Here $connection veriable has database connection object. Now you can use it insert update or delete rows from table.

[php]

$tableName = $resource->getTableName(‘table_name’);
$sql = “Update ” . $tableName . ” Set column_name= ‘”.$coulmn_name.”‘ where entity_id = “.$entityId;
$connection->query($sql);
<pre>[/php]

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.