Apex DMLを使用してレコードaccountsを挿入する

環境
Salesforce

構文
1.account sObjectの作成
Account acct = new Account();
acct.Name =xxx

2.DMLを使用してレコードを挿入する
insert acct

3.DMLステートメントの例外処理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
try {
処理コード
} catch(DmlException e) {
エラーメッセージの出力
}
try { 処理コード } catch(DmlException e) { エラーメッセージの出力 }
try {
処理コード
} catch(DmlException e) {
エラーメッセージの出力
}

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
public class AccountHandler {
public static Account insertNewAccount(String strname){
try {
Account acct = new Account();
acct.Name= strname;
acct.Phone= '1234-010-56';
insert acct;
return acct;
} catch(DmlException e) {
System.debug('A DML exception has occurred' + e.getMessage());
return null;
}
}
}
public class AccountHandler { public static Account insertNewAccount(String strname){ try { Account acct = new Account(); acct.Name= strname; acct.Phone= '1234-010-56'; insert acct; return acct; } catch(DmlException e) { System.debug('A DML exception has occurred' + e.getMessage()); return null; } } }
public class AccountHandler {

    public static Account insertNewAccount(String strname){
        
        try {
            Account acct = new Account();
            acct.Name= strname;
            acct.Phone= '1234-010-56';
            
            insert acct;
            
            return acct;
        } catch(DmlException e) {
            System.debug('A DML exception has occurred' + e.getMessage());
            return null;
        }
        
    }
}

動作確認
[Execute Anonymous (匿名実行)] ウィンドウで、クラス名で静的メソッドをコールするようにステートメントを変更します。
AccountHandler.insertNewAccount('AccountName’);
[Execute (実行)] をクリックします。

Apex

Posted by arkgame