function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Praveen kumar TammaliPraveen kumar Tammali 

Insert records using Batch Apex

Hi All,
How to insert records using batch apex.There is lot of information given to update the existing records.
but i want only isert records 
Thanks
Praveen
Dhriti Moulick 16Dhriti Moulick 16
Hi Praveen,

   You can write test class for your Batch apex in following ways:

  
1.@isTest
   private class BatchClassTest {

    static testMethod void myUnitTest() {

             Object__c  obj = new Object__c(); // initialize your object name
             obj.Field1 = value1;            // Assign field values 
             obj.Field2 = value2;
             obj.field3 = value3;
              ....................
            .......................
 
             insert obj; // insert object values


             BatchClass btclass = new BatchClass ();  // initialize your batch class name
             Test.startTest();
             Database.executeBatch(btclass ,1);   // execute your batch by calling        executeBatch and passing class instance and number of values runs in that batch
             Test.stopTest();
    }
Please let me know if you need any additional help.

Cheers,
Dhriti
 
Praveen kumar TammaliPraveen kumar Tammali
Thanks for ur reply, but i dont want test class. i need batch class to insert 300 records for account?
Kevin CrossKevin Cross
Hello. 

Look at the Iterable implementation of Batch Apex (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm) as I think that is what you want.  You can use a private List<sObject> or specify your type, then create a constructor that receives a list that it sets to the private one.  In your start() method, return the private list.
global class YourBatchClass implements Database.Batchable {
   List<sObject> batchList;
   global YourBatchClass(List<sObject> objList) {
      // modify list if necessary (e.g., trap null)
      if (objList == null) objList = new List<sObject>();      
      this.batchList = objList;
   }
   global Iterable start(Database.BatchableContext info){ 
       return this.batchList; 
   }     
   global void execute(Database.BatchableContext info, List<sObject> scope){
       // do whatever you need to prep scoped records for insert
       // insert scoped records  
   }     
   global void finish(Database.BatchableContext info){     
   } 
}

I hope that helps.

P.S. please forgive any type-o's as I didn't run this in SF, just typed here directly.  Therefore, please use this just as a template for understanding the concept.