Salesforce 关于Apex中【SaveResult】

2022-05-23 17:34:58 浏览数 (2)

1.

在ApexClass中使用【Database.insert(xxxList)】登录或者使用【Database.update(xxxList)】更新多条数据时,如果其中一条有错误,所有登录或者更新都不会成功

代码语言:javascript复制
Database.insert(oppList);

如下往Opportunity表中插入两天数据,第二条因为必须入力项目【CloseDate】没有设定值,所以两条数据都不会插入成功。

代码语言:javascript复制
List<Opportunity> oppList = new List<Opportunity>();
Opportunity oppItem1 = new Opportunity();
oppItem1.Name = 'OppTest003';
oppItem1.StageName = 'Prospecting';
oppItem1.CloseDate = System.today();
oppList.add(oppItem1);

Opportunity oppItem2 = new Opportunity();
oppItem2.Name = 'OppTest004';
oppItem2.StageName = 'Prospecting';
oppList.add(oppItem2);

Database.SaveResult[] srList = Database.insert(oppList);

// 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 Opportunity. '   sr);
        System.debug('>>>>Successfully inserted Opportunity. Opportunity 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.getStatusCode());
            System.debug('>>>>err.getMessage(): '   err.getMessage());
            System.debug('>>>>Opportunity fields that affected this error: '   err.getFields());
        }
    }
}

2.

如下,当第二个参数设定为false时,则会忽视错误,插入没有问题的数据。其中有错误的数据,详细错误信息会保存在【sr.getErrors()】中

代码语言:javascript复制
Database.insert(oppList, false);

代码语言:javascript复制
List<Opportunity> oppList = new List<Opportunity>();
Opportunity oppItem1 = new Opportunity();
oppItem1.Name = 'OppTest003';
oppItem1.StageName = 'Prospecting';
oppItem1.CloseDate = System.today();
oppList.add(oppItem1);

Opportunity oppItem2 = new Opportunity();
oppItem2.Name = 'OppTest004';
oppItem2.StageName = 'Prospecting';
oppList.add(oppItem2);

Database.SaveResult[] srList = Database.insert(oppList, 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 Opportunity. '   sr);
        System.debug('>>>>Successfully inserted Opportunity. Opportunity 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.getStatusCode());
            System.debug('>>>>err.getMessage(): '   err.getMessage());
            System.debug('>>>>Opportunity fields that affected this error: '   err.getFields());
        }
    }
}

0 人点赞