Saturday, April 12, 2014

What is Data Manipulation Language in Apex?

What is Data Manipulation Language in Apex?


Apex Data Manipulation Language (DML). DML enables you to insert, update, delete or restore data in the database.Changes to database records in Force.com are saved using Data Manipulation Language (DML) operations. DML operations allow you to modify records one at a time, or more efficiently in batches of multiple records.The five major DML operation types are listed 
  1. Insert: Creates new records
  2. Update: Updates the values in existing records, identified by Force.com unique identifier (Id) field or a custom field designated as an external identifier.
  3. Upsert: If records with the same unique identifier or external identifier exist, this updates their values. Otherwise, it inserts them.
  4. Delete: Moves records into the Recycle Bin.
  5. Undelete: Restores records from the Recycle Bin.

 Insert: - The Insert statement adds up to 200 records of a single object type to the database. When all records succeed, they contain their new unique identifiers. If any record fails, a DmlException is raised and the database is returned to its state prior to the Insert statement.

try {
Contact c = new Contact(FirstName = 'Justin', LastName = 'Case');
insert c;
Resource__c r = new Resource__c(
Contact__c = c.Id, Hourly_Cost_Rate__c = 75, Region__c = 'West');
insert r;
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, e.getMessage());
}

Update :-  Update saves up to 200 existing records of a single object type. Existing records are identified
by unique identifier (Id).

Resource__c doug = new Resource__c(Name = 'Doug Hole');
insert doug;
doug.Hourly_Cost_Rate__c = 100;
doug.Home_Office__c = 'London';
update doug;

Upsert:- Upsert combines the behavior of the Insert and Update operations on up to 200 records of the same object type. First, it attempts to locate a matching record using its unique identifier or external identifier. If one is found, the statement acts as an Update. If not, it behaves as an Insert.
The syntax of the Upsert statement is identical to Update and Insert, but adds a second, optional argument for specifying an external identifier. If an external identifier is not provided, the record’s unique identifier is used.

Ex:-
Resource__c r = new Resource__c(Resource_ID__c = 1001, Name = 'Terry Bull');
upsert r Resource_ID__c;

Delete and Undelete

Delete and Undelete statements move up to 200 records of the same object type to and from the Recycle Bin, respectively.

Deleting Records

Resource__c terry = new Resource__c(Name = 'Terry Bull');
insert terry;
delete terry;

Undeleting Records

Resource__c terry2 = [ SELECT Id, Name FROM Resource__c WHERE Name LIKE 'Terry%' LIMIT 1 ];
System.debug(terry2.Name + ' exists');
delete terry;
undelete terry;


1 comments:

radha said...

Well expalined. Keep updating salesforce Online Course

Post a Comment

 
| ,