• Salesforce-Apex中的数据操控(DML&数据库方法)


    一.DML

    使用 Data Manipulation Language(简称 DML)(数据操控语言)在 Salesforce 中创建和修改记录

    1.DML Statements(声明):The following DML statements are available.

    • insert
    • update
    • upsert
    • delete
    • undelete
    • merge:Merge 语句将最多三个相同 sObject 类型的记录合并到其中一个记录中,同时删除其他记录,并重新设置关联记录的父级。

    2.DML语句

    • insert:插入记录时,系统会为每条记录分配一个 ID。除了将 ID 值保留在数据库之外,ID 值还会自动填充到在 DML 调用中用作参数的 sObject 变量上。
      ※可以从数据库中检索记录以获取其字段,包括 ID 字段,但这不能通过 DML 来完成,需要使用 SOQL 编写查询语句。
    // Create the account sObject 								
    Account acct = new Account(Name='Acme', Phone='(415)555-1212', NumberOfEmployees=100);								
    // Insert the account by using DML								
    insert acct;								
    // Get the new ID on the inserted sObject argument								
    ID acctID = acct.Id;								
    // Display this ID in the debug log								
    System.debug('ID = ' + acctID);								
    // Debug log result (the ID will be different in your case)								
    // DEBUG|ID = 001D000000JmKkeIAF								
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • update:批量 DML
    // Create a list of contacts								
    List<Contact> conList = new List<Contact> {								
            new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),								
            new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),								
            new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),								
    								
    // Bulk insert all contacts with one DML call								
    insert conList;								
    // List to hold the new contacts to update								
    List<Contact> listToUpdate = new List<Contact>();								
    // Iterate through the list and add a title only								
    //   if the department is Finance								
    for(Contact con : conList) {								
        if (con.Department == 'Finance') {								
            con.Title = 'Financial analyst';								
            // Add updated contact sObject to the list.								
            listToUpdate.add(con);								
        }								
    }								
    // Bulk update all contacts with one DML call								
    update listToUpdate;								
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • upsert:以下upsert 调用时使用 ID 匹配第一个联系人。在 upsert 调用中重用 josh 变量。该变量使用了上一次 insert 调用的记录 ID 来填充,因此在本例中不需要显式设置 ID。
    										
    // Insert the Josh contact										
    Contact josh = new Contact(FirstName='Josh',LastName='Kaplan',Department='Finance');       										
    insert josh;										
    //   Josh's record has been inserted										
    //   so the variable josh has now an ID										
    //   which will be used to match the records by upsert										
    josh.Description = 'Josh\'s record has been updated by the upsert operation.';										
    // Create the Kathy contact, but don't persist it in the database										
    Contact kathy = new Contact(FirstName='Kathy',LastName='Brown',Department='Technology');										
    // List to hold the new contacts to upsert										
    List<Contact> contacts = new List<Contact> { josh, kathy };										
    // Call upsert										
    upsert contacts;										
    // Result: Josh is updated and Kathy is created.
    		
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    Contact jane = new Contact(FirstName='Jane',								
                             LastName='Smith',								
                             Email='jane.smith@example.com',								
                             Description='Contact of the day');								
    insert jane;								
    // 1. Upsert using an idLookup field								
    // Create a second sObject variable.								
    // This variable doesn’t have any ID set.								
    Contact jane2 = new Contact(FirstName='Jane',								
                             LastName='Smith',  								
                             Email='jane.smith@example.com',								
                             Description='Prefers to be contacted by email.');								
    // Upsert the contact by using the idLookup field for matching.								
    upsert jane2 Contact.fields.Email;								
    // Verify that the contact has been updated								
    System.assertEquals('Prefers to be contacted by email.',								
                       [SELECT Description FROM Contact WHERE Id=:jane.Id].Description);
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • delete:通过 delete 语句删除永久记录。已删除的记录不会从 Lightning 平台永久删除,而是在回收站中保存 15 天,可以从回收站中恢复记录。
    Contact[] contactsDel = [SELECT Id FROM Contact WHERE LastName='Smith']; 			
    delete contactsDel;			
    
    
    • 1
    • 2
    • 3

    3.DML语句异常

    如果 DML 操作失败,将返回 DmlException 类型的异常。可以在代码中捕获异常以处理错误情况。
    该示例产生了 DmlException 异常,原因是插入了一个不包含必填名称字段的客户。在 catch 块中捕获了异常。

    try {								
        // This causes an exception because 								
        //   the required Name field is not provided.								
        Account acct = new Account();								
        // Insert the account 								
        insert acct;								
    } catch (DmlException e) {								
        System.debug('A DML exception has occurred: ' +								
                    e.getMessage());								
    }								
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    二.数据库方法

    数据库方法
    Apex 包含了内置的数据库类,该类提供执行 DML 操作和镜像 DML 语句对应项的方法。
    数据库方法是静态的,并在类名上调用。
    Database.insert()
    Database.update()
    Database.upsert()
    Database.delete()
    Database.undelete()
    Database.merge()

    与 DML 语句不同,数据库方法有一个可选的 allOrNone 参数,它允许指定操作是否可以部分成功。当该参数设置为 false 时,如果部分记录集发生错误,将提交成功的记录,并为失败的记录返回错误。另外,部分成功选项不会抛出异常。

    Database.insert(recordList, false);
    
    • 1

    数据库方法返回包含每个记录的成功或失败信息的结果对象。例如,insert 和 update 操作都会返回Database.SaveResult 对象数组。

    Database.SaveResult[] results = Database.insert(recordList, false);					
    upsert 操作返回 Database.UpsertResult 对象					
    delete 操作返回 Database.DeleteResult 对象					
    
    
    • 1
    • 2
    • 3
    • 4
    Database.insert(recordList);			
    =			
    Database.insert(recordList, true);			
    
    
    • 1
    • 2
    • 3
    • 4

    示例:插入部分成功的记录

    // Create a list of contacts									
    List<Contact> conList = new List<Contact> {									
            new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),									
            new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),									
            new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),									
            new Contact()};									
    // Bulk insert all contacts with one DML call									
    Database.SaveResult[] srList = Database.insert(conList, 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 contact. Contact 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('Contact fields that affected this error: ' + err.getFields());									
    	 }								
        }									
    }									
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    三.选择使用 DML 语句还是数据库方法?

    • DML 语句:
      如果希望将批量 DML操作期间发生的任何错误作为立即中断控制流的 Apex 异常抛出(通过使用 try…Catch 块)。这种行为与大多数数据库过程化语言中处理异常的方式类似。
    • Database 类方法:
      如果希望允许批量 DML 操作部分成功,请使用数据库类方法 — 如果记录失败,DML 操作的其余部分仍然可以成功。
      然后,应用程序可以检查被拒记录,并执行重试操作。
      可以编写不抛出 DML 异常错误的代码。
      相反,代码可以使用适当的结果数组来判断成功或失败。与 DML 语句类似,数据库方法还包括支持抛出异常的语法
    // Query for the contact, which has been associated with an account.								
    Contact queriedContact = [SELECT Account.Name 								
                              FROM Contact 								
                              WHERE FirstName = 'Mario' AND LastName='Ruiz'								
                              LIMIT 1];								
    // Update the contact's phone number								
    queriedContact.Phone = '(415)555-1213';								
    // Update the related account industry								
    queriedContact.Account.Industry = 'Technology';								
    // Make two separate calls 								
    // 1. This call is to update the contact's phone.								
    update queriedContact;								
    // 2. This call is to update the related account's Industry field.								
    update queriedContact.Account; 								
    								
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    【含java2023面试题】HashMap、HashTable、ConcurrentHashMap
    C# 在PDF中添加墨迹注释Ink Annotation
    vue全局方法plugins/utils
    DataGridView选中的单元格求和
    【JavaSE】/*基于Java语言的递归运算*/
    Android NDK开发基础
    问题排查:nginx能跑,但是只能跑一会,不能跑多了
    idea放大镜效果当对源码或者平常自己的代码关系
    MATLAB打开历史命令窗口并保持
    免费下载缺失的DLL文件
  • 原文地址:https://blog.csdn.net/nihaixiao/article/details/125435492