The insert DML operation adds one or more sObjects, such as individual accounts or contacts, to your organization’s data.insert is analogous to the INSERT statement in SQL.
The optional opt_allOrNoneparameter specifies whether the operation allows partial success. If you specify false for this parameter and a record fails, the remainder of the DML operation can still succeed. This method returns a result object that can be used to verify which records succeeded, which failed, and why.
Database.SaveResult[] MySaveResult = Database.Insert(MyAccounts, false);The optional opt_DMLOptions parameter specifies additional data for the transaction, such as assignment rule information or rollback behavior when errors occur during record insertions.
//AssignmentRuleHeader //UseDefaultRule Database.DMLOptions dmo = new database.DMLOptions(); dmo.AssignmentRuleHeader.UseDefaultRule= true; Lead l = new Lead(Company='ABC', LastName='Smith'); l.setOptions(dmo); insert l;
For more information, see Database DMLOptions Properties.
An array of SaveResult objects is returned with the insert and update database methods. Each element in the SaveResult array corresponds to the sObject array passed as the sObject[] parameter in the database method, that is, the first element in the SaveResult array matches the first element passed in the sObject array, the second element corresponds with the second element, and so on. If only one sObject is passed in, the SaveResults array contains a single element.
A SaveResult object has the following methods:
| Name | Type | Description |
|---|---|---|
| getErrors | Database.Error [] | If an error occurred, an array of one or more database error objects providing the error code and description. For more information, see Database Error Object Methods. |
| getId | ID | The ID of the sObject you were trying to insert or update. If this field contains a value, the object was successfully inserted or updated. If this field is empty, the operation was not successful for that object. |
| isSuccess | Boolean | A Boolean that is set to true if the DML operation was successful for this object, false otherwise. |
Account newAcct = new Account(name = 'Acme'); try { insert newAcct; } catch (DmlException e) { // Process exception here }
Account a = new Account(name = 'Acme'); Database.SaveResult[] lsr = Database.insert(new Account[]{a, new Account(Name = 'Acme')}, false); // Iterate through the Save Results for(Database.SaveResult sr:lsr){ if(!sr.isSuccess()) Database.Error err = sr.getErrors()[0]; }