
Use DML to insert multiple records into a Salesforce database
Acme Inc. has opened three new locations in Texas. Acme needs to insert the new accounts into its database. Create a class and one method that creates three new accounts and adds them to the database.
- Create a public Apex class named AccountHandler
- Add a public static method to the class:
- Name: insertAccount
- Include a parameter for the number of new accounts:
- Data type: integer
- Create a list of Account records:
- List name: addAccounts
- Use a while loop to add three new Accounts to the list, where n is a value that is incremented by 1 during each iteration of the loop:
- Name: Acme Inc n
- AccountNumber: A000n
- Hint: You did something like this when you created three new Tea Factory stores.
- Write one DML statement that inserts all three records into the database at one time
- Run your insertAccount method.
Error Message:
We can't find code that creates an 'addAccounts' list, adds three accounts to the 'addAccounts' list, and then inserts the 'addAccounts' list.
Code:
What am I doing wrong?public class AccountHandler {
public static void insertAccount(Integer numAccts) {
List<Account> addAccounts = new List<Account>();
Integer counter = 1;
while(counter <= 3) {
Account a = new Account();
a.Name = 'Acme Inc ' + counter;
a.AccountNumber = 'A000' + counter;
addAccounts.add(a);
counter++;
}
if(addAccounts.size() > 0) {
Database.insert(addAccounts);
}
}
}
35 réponses
This worked for me.