Apex offers two ways to perform DML operations: using DML statements or Database class methods. This provides flexibility in how you perform data operations. DML statements are more straightforward to use and result in exceptions that you can handle in your code. This is an example of a DML statement to insert a new record.
// Create the list of sObjects to insert List<Account> acctList = new List<Account>(); acctList.add(new Account(Name='Acme1')); acctList.add(new Account(Name='Acme2')); // DML statement insert acctList;
This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
// Create the list of sObjects to insert List<Account> acctList = new List<Account>(); acctList.add(new Account(Name='Acme1')); acctList.add(new Account(Name='Acme2')); // DML statement Database.SaveResult[] sr = Database.insert(acctList, false); // Iterate through each returned result for (Database.SaveResult sr : srList) { if (sr.isSuccess()) { // Operation was successful, so get the ID of the record that was processed System.debug('Successfully inserted account. Account ID: ' + sr.getId()); } else { // Operation failed, so get all errors for(Database.Error err : sr.getErrors()) { System.debug('The following error has occurred.'); System.debug(err.getStatusCode() + ': ' + err.getMessage()); System.debug('Account fields that affected this error: ' + err.getFields()); } } }
One difference between the two options is that by using the Database class method, you can specify whether or not to allow for partial record processing if errors are encountered. You can do so by passing an additional second Boolean parameter. If you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered. By default, this optional parameter is true, which means that if at least one sObject can’t be processed, all remaining sObjects won’t and an exception will be thrown for the record that causes a failure.
The following helps you decide when you want to use DML statements or Database class methods.