Mytutorialrack

Database SaveResult

What is Database Saveresult in Salesforce ?

In Salesforce, the Database.SaveResult class is used to capture the results of a database operation. It is typically used when performing DML (Data Manipulation Language) operations, such as inserting, updating, or deleting records.

When executing DML statements in Salesforce, exceptions are thrown if an operation fails for any of the records being processed. In such cases, the entire operation is rolled back, affecting all the records involved.

However, when using methods from the Database class, a different behavior can be observed. These methods provide an option for partial success during record processing, allowing some records to be processed successfully while others may encounter failures.

Unlike DML statements, Database class methods do not throw exceptions in the case of partial processing. Instead, they return a list of errors that occurred on the failed records.

To access the error information, the Database class methods return specific objects such as SaveResult for insert and update operations. These result objects have a method called getErrors(), which returns a list of Database.Error objects. These Database.Error objects contain detailed information about the encountered failures.

By leveraging the getErrors method, developers can retrieve the error details and take appropriate actions to handle the failed records in a more granular manner, allowing for better error handling and the possibility of salvaging the operation by rectifying the specific issues encountered.

Here’s an example of how to use Database SaveResult in Salesforce Apex code:

// Create a list of records to insert/update/delete
List<Contact> contactsToInsert = new List<Contact>();
// Populate the list with contact records
for(Integer i=1;i<=10;i++)
{
	Contact con=new Contact();
    if(math.mod(i, 2) == 0)
    {
        con.firstname='Even '+i;
        con.lastName='Mytutorialrack';
        con.mailingCountry='USA';
    }
	else 
    {
        con.firstName='Odd '+i;
    }
    contactsToInsert.add(con);
}
// Perform the DML operation and capture the results
Database.SaveResult[] saveResults = Database.insert(contactsToInsert, false);

// Iterate over the save results
for (Database.SaveResult saveResult : saveResults) {
    if (saveResult.isSuccess()) {
        System.debug('Record Succesffully created '+saveResult.getId());
    } else {
        // Record failed to insert/update
        for (Database.Error error : saveResult.getErrors()) {
        System.debug('Record Failed'+error);
        }
    }
}

Advantages of using Database.SaveResult

The Database.SaveResult class in Salesforce provides several benefits when working with DML operations. Here are some advantages of using Database.SaveResult:

  1. Error Handling: Database.SaveResult allows you to handle errors gracefully. When performing DML operations, there can be various reasons for records to fail, such as validation rules, triggers, or duplicate rules. With Database.SaveResult, you can easily identify which records failed and access the corresponding error messages to take appropriate action.
  2. Id Access: Database.SaveResult provides access to the IDs of the successfully saved records. You can use saveResult.getId() to retrieve the ID of each saved record. This is useful when you need to perform further operations or establish relationships with other records based on the saved IDs.

Overall, Database.SaveResult helps improve the robustness and reliability of your DML operations by providing detailed information about the success or failure of individual records, allowing for better error handling and control over the data manipulation process.

// Create a list of records to insert/update/delete
List<Contact> contactsToInsert = new List<Contact>();
// Populate the list with contact records
for(Integer i=1;i<=10;i++)
{
	Contact con=new Contact();
    if(math.mod(i, 2) == 0)
    {
        con.firstname='Even '+i;
        con.lastName='Mytutorialrack';
        con.mailingCountry='USA';
    }
	else 
    {
        con.firstName='Odd '+i;
    }
    contactsToInsert.add(con);
}

// Perform the DML operation and capture the results
Database.SaveResult[] saveResults = Database.insert(contactsToInsert, false);

// Separate successful and failed records
List<Id> successfulRecords = new List<Id>();
List<Database.Error> failedRecordsErrors = new List<Database.Error>();

// Iterate over the save results
for (Database.SaveResult saveResult : saveResults) {
    if (saveResult.isSuccess()) {
        // Record was successfully inserted/updated
        // Access the saved record ID using saveResult.getId()
        successfulRecords.add(saveResult.getId());
    } else {
        // Record failed to insert/update
        failedRecordsErrors.addAll(saveResult.getErrors());
    }
}

// Output the successful records
System.debug('Successful Records: ' + successfulRecords);

// Output the error messages of failed records
for (Database.Error error : failedRecordsErrors) {
    System.debug('Failed Record Error: ' + error.getMessage());
}

Methods of Database SaveResult

In Salesforce, the Database.SaveResult class provides several methods to access and handle the results of a database operation. Here are the commonly used methods available in the SaveResult class:

  1. isSuccess(): Returns a Boolean value indicating whether the operation was successful (true) or not (false).
  2. getId(): Retrieves the ID of the successfully saved record. This method is useful for accessing the ID of an individual record.
  3. getErrors(): Returns an array of Database.Error objects representing the errors associated with a failed record. You can iterate over this array to access the error messages and details.
Become a Salesforce Developer with this ONE COURSE

Share:

Recent Posts