Magento 2 How to create custom query that is the question sometime is popped up on your head. Here is how I create my own custom queries in Magento 2.
Currently, I figured out two ways :
1/ Take advantage of using Magento Resource Connection.
    $themeId=3;
    $this->_resources = \Magento\Framework\App\ObjectManager::getInstance()
        ->get('Magento\Framework\App\ResourceConnection');
    $connection= $this->_resources->getConnection();
    $select = $connection->select()
        ->from(
            ['o' =>  $this->_resources->getTableName('theme')]
        )->where('o.theme_id=?',$themeId);
    $result = $connection->fetchAll ($select);
    var_dump($result);
You can change the query to insert, update or delete according to zend framework. It’s just an example code, you should put $connection in a property of a helper class and use it from this help class.
2/The other way is reusing Magento Object Manager to create a collection:
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');//insert your custom resource model
    $collection = $productCollection->create()
        ->addAttributeToSelect('*')
        ->load();
    foreach ($collection as $product){
        echo 'Name  =  '.$product->getName().'<br>';
    }
Happy coding !
 
  
             
                         
                         
                 
                
COMMENTS