0

According to the official document -

https://developer.salesforce.com/docs/atlas.en-us.198.0.apexcode.meta/apexcode/apex_transaction.htm

I understand that if there is any error in a transaction all the DML statement are rolled back and nothing is committed to the database. After reading this document:

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_database.htm

I read that if we give an additional parameter- false while calling a Database class to insert then we can do a partial commit to database and the record with error is rolled back.

So how does a Database.Insert operation with false attribute behaves in a transaction as compared to the DML operation - insert? Would the Database class allow a partial commit if there is any error in a transaction?

1

Yes database.insert allow the partial insert of records. eg you insert 500 records and and in 1 records you will get error then other records will be inserted successfully if you pass parameter false. if you set it to true then it will work as insert statement.

Second difference in insert statement if you get exception you need to handle that other wise you will get a message on UI but with Database.insert you can iterate over each records and get error message something like this

// DML statement
Database.SaveResult[] srList = Database.insert(acctList, false);

// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
    }
    else {
        // Operation failed, so get all errors                
        for(Database.Error err : sr.getErrors()) {
            System.debug('The following error has occurred.');                    
            System.debug(err.getStatusCode() + ': ' + err.getMessage());
            System.debug('Account fields that affected this error: ' + err.getFields());
        }
    }
}

Other limits remain same for both. Normally when we want to create Dataloader type functionality we can use Database class

2
  • Should we not use Database.Insert with transactions? As it will commit the records to the database even if something fails some where else in the code which is part of the same transaction. Thanks! – SfdcBat Oct 26 '16 at 4:06
  • 1
    @SfdcBat no you misunderstand here. If something fails in same transaction then complete transaction rollback. But if you insert a list and few records fails then database.insert will insert the correct record in system. also error in DML will stop the execution flow but Datbase.insert will not stop the execution flow. – Tushar Sharma Oct 26 '16 at 4:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.