Data Manipulation

Data Manipulation and Error Handling in Salesforce

In Salesforce, to fetch data using apex we require DML operations. Apex allows DML operations on both List<Sobject> and single sObject to update data in the database. 

DML stands for Data Manipulation Language, various DML operations in apex are: - 

DML Operation  Usage 
Insert[Sobject | List<Sobject>]  Insert a new record 
Update [Sobject | List<Sobject>]  Update existing records using ID 
Delete [Sobject | List<Sobject>]  Delete records using ID 
Upsert [Sobject | List<Sobject>]  Update/Insert records (If record ID matches, then update the record, otherwise insert a new record) 
Merge Sobject1 Sobject2  Merge up to 3 records in a single record 
Undelete [Sobject | List<Sobject>]  Retrieves a record or list previously deleted from recycle bin 

 We have a list of opportunity records and we want to make some changes to that List, we can do so by using DML operations and changes will be reflected in our database. 

dont miss out iconDon't forget to check out: How Does Salesforce Secure Your Data? Learn Here!

Database Methods

Apex provides the options to use Database methods in addition to DML operations. Database methods return the results of the data operation. These result objects contain useful information about the data operation for each record, such as whether the operation was successful or not, and any error information. 

Syntax:- 

Database.insert[Sobject | List<Sobject>] 

 In the Database method, we have another parameter which controls the atomicity, by adding true to follow atomicity and false to avoid it. 

Each type of operation returns a specific result object type, as mentioned in the table below:- 

Operation  Return Type 
Insert,update  SaveResult 
upsert  UpsertResult 
merge  MergeResult 
delete  DeleteResult 
undelete  UndeleteResult 

Transaction Control

In transaction Control, all the requests are delimited by a trigger, class method, web service, visualforce page that executes the apex code. If the request completes successfully the changes are committed to the database and if not then all the database changes are rolled back. 

dont miss out iconCheck out another amazing blog by Bhawana here: Apex Triggers in Salesforce | Here's the Ultimate Salesforce Guide

Error Handling

Apex uses the try, catch method and finally block to handle errors. DML statements return run-time exceptions if something went wrong in the database during the execution of the DML operations. The exceptions in the code can be handle by wrapping up DML statements within try-catch blocks. 

For example:- 

Account a = new Account(Name=’Acme’); 
try { 
    Insert a; 
    }catch(DMLException e) { 
    //Process exception here 
}

 

Responses

Popular Salesforce Blogs