7.Apex中的数据操控(DML&数据库方法)

本文详细介绍了Apex编程语言中的DML语句和数据库方法,包括如何创建、更新、合并和删除Salesforce记录。Apex是一种与Java类似的强类型语言,用于实现业务逻辑。DML语句如insert、update、upsert和delete用于操作数据,而数据库方法提供了更多的灵活性,如部分成功选项。文章还讨论了在何时选择使用DML语句或数据库方法的策略。
摘要由CSDN通过智能技术生成

前言

什么是Apex?

Apex是一种强类型的,面向对象的编程语言,开发人员通过Apex表现业务逻辑来补充Salesforce平台所需的功能。
Apex与Java很像,可以通过各种用户启动的事件来触发,例如记录更新,单击按钮,对象触发或外部Web服务请求。
Apex无法在生产组织中进行自定义,必须通过沙盒进行更改和部署,并满足测试范围。Visualforce可以直接在生产环境中进行自定义(但不推荐)。

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

  • 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;								

  • 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.
		
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);
 
  • delete:通过 delete 语句删除永久记录。已删除的记录不会从 Lightning 平台永久删除,而是在回收站中保存 15 天,可以从回收站中恢复记录。
Contact[] contactsDel = [SELECT Id FROM Contact WHERE LastName='Smith']; 			
delete contactsDel;			

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());								
}								

二.数据库方法

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

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

Database.insert(recordList, false);

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

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

Database.insert(recordList);			
=			
Database.insert(recordList, true);			

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

// 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());									
	 }								
    }									
}									

三.选择使用 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; 								
								


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值