Activity Forums Salesforce® Discussions Use of Database.Insert in SOQL?

  • Aman

    Member
    July 11, 2017 at 2:23 pm

    Hello Saloni ,

    One difference between the two options is that by using the Database class method, you can specify whether or not to allow for partial record processing if errors are encountered.The syntax of Database.insert is Database.insert(acctList, Parameter).The default value for this parameter is true,which means that if at least one sObject can’t be processed, all remaining sObjects won’t and an exception will be thrown for the record that causes a failure.If you specify false for this parameter and if a record fails, the remainder of DML operations can still succeed. Also, instead of exceptions, a result object array (or one result object if only one sObject was passed in) is returned containing the status of each operation and any errors encountered.

    List<Account> acctList = new List<Account>();
    acctList.add(new Account(Name='Acme1'));
    acctList.add(new Account(Name='Acme2'));
    // 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());
    }
    }
    }

  • Parul

    Member
    September 19, 2018 at 6:25 pm

    Hi

    1.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.

    2.If DML database methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.

  • shariq

    Member
    September 19, 2018 at 11:00 pm

    Hi,

    Basic use of this -

    If DML database methods (Database.insert) used, then if error occurs the remaining records will be inserted / updated means partial DML operation will be done.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos