Newer Version Available
DML Statements vs. Database Class Methods
This is an example of a DML statement to insert a new record.
1// Create the list of sObjects to insert
2List<Account> acctList = new List<Account>();
3acctList.add(new Account(Name='Acme1'));
4acctList.add(new Account(Name='Acme2'));
5
6// DML statement
7insert acctList;This is an equivalent example to the previous one but it uses a method of the Database class instead of the DML verb.
1// Create the list of sObjects to insert
2List<Account> acctList = new List<Account>();
3acctList.add(new Account(Name='Acme1'));
4acctList.add(new Account(Name='Acme2'));
5
6// DML statement
7Database.SaveResult[] srList = Database.insert(acctList, false);
8
9// Iterate through each returned result
10for (Database.SaveResult sr : srList) {
11 if (sr.isSuccess()) {
12 // Operation was successful, so get the ID of the record that was processed
13 System.debug('Successfully inserted account. Account ID: ' + sr.getId());
14 }
15 else {
16 // Operation failed, so get all errors
17 for(Database.Error err : sr.getErrors()) {
18 System.debug('The following error has occurred.');
19 System.debug(err.getStatusCode() + ': ' + err.getMessage());
20 System.debug('Account fields that affected this error: ' + err.getFields());
21 }
22 }
23}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.
- Use DML statements if you want any error that occurs during bulk DML processing to be thrown as an Apex exception that immediately interrupts control flow (by using try. . .catch blocks). This behavior is similar to the way exceptions are handled in most database procedural languages.
- Use Database class methods if you want to allow partial success of a bulk DML operation—if a record fails, the remainder of the DML operation can still succeed. Your application can then inspect the rejected records and possibly retry the operation. When using this form, you can write code that never throws DML exception errors. Instead, your code can use the appropriate results array to judge success or failure. Note that Database methods also include a syntax that supports thrown exceptions, similar to DML statements.