Apex (DML) Data Manipulation Language

Apex Data Manipulation Language

Invoice_Statement__c inv = new Invoice_Statement__c(Description__c='My new invoice');

// Insert the invoice using DML.
insert inv;
After the invoice statement is inserted, the sObject variable inv will contain the ID of the new invoice statement.

// First get the new invoice statement
Invoice_Statement__c inv = [SELECT Status__c FROM Invoice_Statement__c
WHERE Description__c='My new invoice'];
// Update the status field
inv.Status__c = 'Negotiating';
update inv;

// First get the new invoice statement
Invoice_Statement__c inv = [SELECT Status__c FROM Invoice_Statement__c
WHERE Description__c='My new invoice'];
delete inv;

Invoice_Statement__c inv = [SELECT Status__c FROM Invoice_Statement__c
WHERE Description__c='My new invoice' ALL ROWS];
undelete inv;

Apex supports other DML operations such as merge and upsert

Database DML Methods

Invoice_Statement__c inv1 = new Invoice_Statement__c(Description__c='My new invoice');
Invoice_Statement__c inv2 = new Invoice_Statement__c(Description__c='Another invoice');
// Insert the invoice using DML.
Database.SaveResult[] lsr = Database.insert( new Invoice_Statement__c[]{inv1, inv2}, false);
// Iterate through the results and get the first error for each failed record.
for (Database.SaveResult sr:lsr){
if(!sr.isSuccess())
Database.Error err = sr.getErrors()[0];
}


Invoice_Statement__c[] invs = [SELECT Id FROM Invoice_Statement__c WHERE Description__c='My new invoice' OR Description__c='Another invoice'];
// Delete the invoices returned by the query.
Database.DeleteResult[] drl = Database.delete(invs, false);
// Iterate through the results and get the first error for each failed record.
for (Database.DeleteResult dr:drl){
if(!dr.isSuccess())
Database.Error err = dr.getErrors()[0];
}

Invoice_Statement__c[] invs = [SELECT Status__c FROM Invoice_Statement__c
WHERE Description__c='My new invoice' OR Description__c='Another invoice'
ALL ROWS];
// Restore the deleted invoices.
Database.UndeleteResult[] undelRes = Database.undelete(invs, false);
// Iterate through the results and get the first error for each failed record.
for (Database.UndeleteResult dr:undelRes){
if (!dr.isSuccess())
Database.Error err = dr.getErrors()[0];
}

When to Use DML Statements and Database DML Statements
Typically, you will want to use Database methods instead of DML statements if you want to allow partial success of a bulk DML operation by setting the opt_allOrNone argument to false. In this way, you avoid exceptions being thrown in your code and you can inspect the rejected records in the returned results to possibly retry the operation.

DATABASE METHODS – Allow partial Success.

Comments

Popular Posts