October 31, 2016 by LanceShi
1.3 Use DML to manipulate data
SObjects are records in Salesforce platform. So they can definitely be persisted in Salesforce’s cloud database. The approach, is by using DML statements or Database class methods. Like SObject, DML statement is first class citizen in Apex. They will be treated as normal statements, instead of just strings in most other programming languages.
Let’s take a look at the code.
Merchandise__c mer = new Merchandise__c(); mer.name = 'Bag'; mer.Original_Price__c = 100; mer.Discount_Type__c = 'Half price'; mer.Discounted_Price__c = mer.Original_Price__c * 0.5; insert mer; mer.Discounted_Price__c -= 10; //further discount update mer; Merchandise__c mer2 = new Merchandise__c(); mer2.name = 'clothes'; mer2.Original_Price__c = 150; mer2.Discount_Type__c = 'Normal price'; mer2.Discounted_Price__c = mer.Original_Price__c; mer.Discounted_Price__c += 10; //further discount is over now; List<Merchandise__c> merList = new List<Merchandise__c>(); merList.add(mer); merList.add(mer2); upsert merList;
You should be able to see two new records created in Salesforce after executing this piece of code.
A bit explanation
If you are familiar with Database, you will probably find insert and update very familiar to you. If not, it is still easy to guess by their meaning. Insert means add new record into database while update means update an existing one. Please be aware that all the DML operators can apply to either one record, or a list of records. And preferably, if you can, always try to do it on a list of record. We will explain the reason later in bulkification post.
Upsert is something new in Apex. It simply means, if the record is new, insert it, or otherwise, update.
Besides insert, update and upsert, you can also do delete. Delete simply means delete a record. It is also easy to use.
Create a record and then delete it. See how delete works.