[SalesForce] Assigning an integer variable a value from dynamic SOQL query

I was hoping I can get some help.

So I have a wrapper where populating an integer variable inside a for-loop, with a SQL COUNT() query works well. example:

eachwrap.numOpsPM = [SELECT Count() from operational_projects__c where Project_Manager_Lookup__c =:StringID ];

Now, I want to add filters dynamically, so I change it to what's below. It doesn't work, since the result is a list.

soqlpm = 'SELECT Count() from operational_projects__c where Project_Manager_Lookup__c =:StringID '    
eachwrap.numOpsPM = database.query(SoqlPM)

I've tried making a temporary list variable to hold the list value, and then convert it back to integer.

varOpstemp= database.query(soqlPM) ;
if (varOpsTemp.size() >0 ){
           eachwrap.numOpsPM = integer.valueof(varOpsTemp[0]);
}

This doesn't work, but instead gives me a "use countQuery() for [select count()…] queries" Error, in my exception capture.

Obviously I'm going about this the wrong way. I couldn't find anything on countQuery() at ALL. Can someone point me in the right direction?

Best Answer

You're looking for the Database.countQuery method.

eachwrap.numOpsPM = database.countQuery(SoqlPM);