How to get the default core write and read resources in Magento 2

- Magento 2

Magento 2 Development

Since Magento 2 relies on the concept of resources to interact with database, you can easily get the  global resource and use it for playing with SQL queries or execute directly.

In order to achieve this goal, you have to inject the object resource  Magento\Framework\App\Resource inside di.xml.

In the following example, we use a custom action of the MassDelete controller:

 

Now,  get the resource and put it to the class variable inside the action:

Get a stream or resource for reading / writing :

 Now:

  • get the name of a table that concat the prefix

  •  fetch a use select statement

or a custom query:

More tips from Magento 2 Developer’s Cookbook

Source