Tuesday, March 12, 2013

Inserting and Deleting Bulk records using Dynamic Apex


Visualforce Page:

<apex:page controller="bulkclcs" >
 <apex:form >
     <apex:commandButton value="Insert 15000 records" action="{!insertbulk}"/>
     <apex:commandButton value="Delete them" action="{!deletebulk}"/>
 </apex:form>
</apex:page>

Apex Class:

public with sharing class bulkclcs {

    public PageReference deletebulk() {     
        delbatchcls obj = new delbatchcls();
        database.executebatch(obj,100);
        return null;
                                                     }
    public PageReference insertbulk() {   
        globalbatchcls obj = new globalbatchcls();       
        database.executebatch(obj);   
        return null;
                                                     }
                                                 }

----------------------------------------------------------

global class globalbatchcls implements Database.batchable<sobject>{
global List<Account> start(Database.batchableContext bc){
       LIst<Account> lst= new List<Account>();
       for(integer i=0; i<15000; i++){         
           Account a = new Account();
           a.name='Test'+i;
            lst.add(a);
                                                 }         
       return lst;
                                                                                         }
global void execute(Database.batchableContext bc, List<Account> lst){
insert lst;
                                                                                                     }
global void finish(Database.batchableContext bc){
                                                                   }
                                                                                                                        }
---------------------------------------------------------------------------

global class delbatchcls implements database.batchable<sobject>{
global database.querylocator start(Database.BatchableContext bc ){
string searchedString = 'Test';
System.debug('Select id from Account where name LIKE \'%'+ searchedString + '%\'');
return database.getquerylocator('Select id from Account where name LIKE \'%'+ searchedString + '%\'');
                                                                                                  }
global void execute(Database.BatchableContext bc, List<Account> lst ){
delete lst;
                                                                                                          }
global void finish(Database.BatchableContext bc ){
                                                                        }
                                                                                            }

No comments:

Post a Comment