Wednesday, January 22, 2014

What is the difference between database.insert and insert

What is the difference between database.insert and insert

insert is the DML statement which is same as databse.insert. However, database.insert gives more flexibility like rollback, default assignment rules etc. we can achieve the database.insert behavior in insert by using the method setOptions(Database.DMLOptions)
Important Difference:

If we use the DML statement (insert), then in bulk operation if error occurs, the execution will stop and Apex code throws an error which can be handled in try catch block.
If database DML methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.

The Database DML methods take a single sObject or a list of sObjects as their first argument. They also take a second optional Boolean argument called opt_allOrNone that specifies whether the operation allows for partial success. If set to false and a record fails, the remainder of the DML operation can still succeed. The Database DML methods return the results of the DML operation performed.
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); 

No comments:

Post a Comment