'Create a dynamic SOQL Query using variable objects

I'm trying to execute a dynamic soql query using variable objects. In my visualforce page i have tow apex:selectlist, the first one contains a list of objects, when i select one object from this list, i refresh the second list to display selected object's fields. The apex:inputText contains text to search in selected field.

visual force code:

<apex:selectList id="listObjects" value="{!selectedObject}" size="1">
    <apex:selectOptions value="{!allObjetcs}"></apex:selectOptions>
</apex:SelectList> 
<apex:selectList id="listFields" value="{!selectedField}" size="1">
    <apex:selectOptions value="{!allFields}"></apex:selectOptions>
</apex:SelectList> 
<label>Text to search : </label><apex:inputText id="textResearch" value="{!textResearch}" /> 
<button id="searchButton" type="button">{!$Label.SEARCH}</button> 

apex code :

public void search() {
        result = new List<SearchWrapper>();
        System.debug('>>>>>> ALK - in search ');
        String query = 'Select Id, ' + selectedField + ' from ' + selectedObject + ' where ' + selectedField + ' like \'%' + textResearch + '\'%';
        System.debug('>>>>>> ALK - Query : ' + query);
        List<sObject> = (sObject) Database.query(query);

}

Please how can i cast Database.query(query) and how can i execute this dynamic query.

Thanks for all.



Solution 1:[1]

if you are using a local variable in your query you must put ':' before that. like this:

String value = 'test';
List<something> result = [select id from something where name = :value];

Solution 2:[2]

Try below code. If field list if multiselect, you might have to iterate over the selectedField variable and form a string of field names separated by comma.

String query = 'select '+String.valueOf(selectedField)+' From '+selectedObject+' WHERE Name = \'' + textResearch+'\'';
List<sObject> recordList = Database.query(query);

Solution 3:[3]

public void search() {
    result = new List<SearchWrapper>();
    String query = 'Select ' + selectedField + ' from ' + selectedObject + ' where ' + selectedField + ' like \'%' + textResearch + '%\'';
    System.debug('>>>>>> Query : ' + query);
    List<sObject> l = Database.query(query);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daniel
Solution 2 Victor
Solution 3 figosat