先是实例化一个Account对象,然后进行插入数据操作,然后是数据查询操作
Account a = new Account(Name = ‘Acme’, BillingCity = ‘San Francisco’);
insert a;
sObject s = [SELECT Id, Name FROM Account WHERE Name = ‘Acme’ LIMIT 1];
ID id = s.ID;
Account convertedAccount = (Account)s;
convertedAccount.name = ‘Acme2’;
update convertedAccount;
Contact sal = new Contact(FirstName = ‘Sal’, Account = convertedAccount);
DML Statements vs. Database Class Methods
//DML Statements
// Create the list of sObjects to insert
List acctList = new List();
acctList.add(new Account(Name=’Acme1’));
acctList.add(new Account(Name=’Acme2’));
// DML statement
insert acctList;
//Database Class Methods
// Create the list of sObjects to insert
List acctList = new List();
acctList.add(new Account(Name=’Acme1’));
acctList.add(new Account(Name=’Acme2’));
//第二个参数布尔类型的值是确定是否所有正确才插入
Database.SaveResult[] srList = Database.insert(acctList, 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());
}
}
}
下面是数据的插入和更新操作
MyPosition__c a = new MyPosition__c(Name = ‘Acme’, MyMin_Pay__c = 1,MyMax_Pay__c=2);
insert a;
MyPosition__c aa = [SELECT Name from MyPosition__c where NAME=’aCME’ limit 1];
System.debug(aa.Name);
aa.Name = ‘aaaa’;
update aa;
MyPosition__c aaa = [SELECT Name from MyPosition__c where NAME=’aaaa’ limit 1];
System.debug(aaa.Name);
下面这个是插入相关联的数据
try {
Account acct = new Account(Name=’SFDC Account’);
insert acct;
ID acctID = acct.ID;
//这里通过一个外键来插入相关联的数据
Contact con = new Contact(
FirstName='Joeasdfasdfasfasgfsdgds',
LastName='Smith',
Phone='415.555.1212',
AccountId=acctID);
insert con;
} catch(DmlException e) {
System.debug(‘An unexpected error has occurred: ’ + e.getMessage());
}
下面这个是更新相关的数据操作
try {
// Query for the contact, which has been associated with an account.
Contact queriedContact = [SELECT Account.Name
FROM Contact
WHERE FirstName = ‘Joeasdfasdfasfasgfsdgds’ AND LastName=’Smith’
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;
} catch(Exception e) {
System.debug(‘An unexpected error has occurred: ’ + e.getMessage());
}