[SalesForce] where do I use Database. Methods

I m trying to understand where we use following Database.Methods. I know if we want to insert a record to an object we use DML Statement. What i want to know is why/where we use Database. methods. It might be silly question.
Database.saveResults
Database.insert
Database.query
Database.Query
Database.error

really appreciate the inputs. Thanks a ton in advance.

Best Answer

These methods give you additional options if you want to something other than the default behaviour the DML Statements give, such as...

  • allowFieldTruncation

    Specifies the truncation behavior of large strings.

  • assignmentRuleHeader

    Specifies the assignment rule to be used when creating a case or lead.

  • emailHeader

    Specifies additional information regarding the automatic email that gets sent when an events occurs.

  • localeOptions

    Specifies the language of any labels that are returned by Apex.

  • optAllOrNone

    Specifies whether the operation allows for partial success.

So you have three options

  • Use the default DML statements (no control)
  • Use the Database methods e.g. Database.insert(List records, Boolean allOrNone)
  • Use the Database methods e.g. Database.insert(LIst records, DMLOptions options)

Depending on the options you want to control. You also get additional information returned from these methods that allow you to inspect the results of the operation at an individual record level, for example SaveResult. Here is the sample from the documentation around the use of the allOrNone option...

// Create two accounts, one of which is missing a required field
Account[] accts = new List<Account>{
    new Account(Name='Account1'),
    new Account()};
Database.SaveResult[] srList = Database.insert(accts, 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());
        }
    }
}
Related Topic