使用 Data Manipulation Language(简称 DML)(数据操控语言)在 Salesforce 中创建和修改记录
1.DML Statements(声明):The following DML statements are available.
2.DML语句
// 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
// 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;
// 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);
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());
}
}
}
// 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;