Site icon WedgeCommerce

DML operation using the database class

DML is a basic term when we are talking about SQL. And the same goes for Salesforce too. We use DML operations to manipulate the records. However, most of the developers know about the standard method for DML, i.e. using the keywords. However, there is another method for doing the same, which is not very much in use. This method is doing DML operation using the database class.

APEX Code

For this particular example, like I said earlier, we are going to use the Database class of APEX. This class has been used to interact with the database without using the static queries. Below is the code for the example.

public class dmltest {

    public list accs { get; set;}
    public map responseList { get; set;}
    public boolean renderres { get; set;}
    
    public dmltest(){
	accs = new list();
        accs.add(new account());
        accs.add(new account());
        accs.add(new account());
        renderres = false;
    }
    
    public void save(){
        responseList = new map();
        integer i=0;
        Database.SaveResult[] srs = database.insert(accs,false);
        for(Database.SaveResult sr : srs) {
            if (sr.isSuccess()) {
                responseList.put(i++,'Successfully Created account with ID: ' + sr.getId());
            }
            else {
                for(Database.Error err : sr.getErrors()) {
                    responseList.put(i++,'Error:' +err.getStatusCode() + ' : '+ err.getFields());
                }
            }
        }
    }
}

In this code, we have used the Database class and inserted using the insert method. First parameter here is the list of sObjects that we want to insert. The second parameter in this function is called allOrNone. The use of this parameter is to set whether to skip the records with an exception or to skip the complete batch if an exception occurs on any one record. Setting it to false will skip the individual records.

VisualForce Code

<apex:page controller="dmltest">
    <apex:form >
        <table>
            <apex:repeat value="{!accs}" var="a">
                <tr>
                    <td>
                        Name
                    </td>
                    <td>
                        <apex:inputText value="{!a.name}"/>
                    </td>
                </tr>
            </apex:repeat>
        </table>
        <apex:commandButton action="{!save}" value="Save" rerender="response"/>
    </apex:form>
    <apex:dataList value="{!responseList}" var="res" id="response">
        <apex:outputText value="{!res}:{!responseList[res]}"/>
    </apex:dataList>
</apex:page>

Output

The output of the above code looks something like this:

Support

That’s all about performing DML operation using the database class, for any further queries feel free to contact us at:

https://wedgecommerce.com/contact-us/

Or let us know your views about this blog in the comments section below.

Exit mobile version