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
aaryansriaaryansri 

how to use DML operation behind governor limits without using bacth apex

hi i am using below code to insert more than governor limits.
getting error of System.LimitException: Too many DML statements: 151: AnonymousBlock: line 12, column 1.

faculty__c fac=new faculty__c();
for(integer i=0;i<=300;i++){
string name='raja';
integer salary=10000;
try{

fac.name=name;
fac.salary__c=salary;
insert fac;
}
catch(Exception e){
system.debug('Hello');
}
}
Subhash GarhwalSubhash Garhwal
Hi ashok,
You need to add faculty__c records in list and than insert it outside of for loop

List<faculty__c> facs = new List<faculty__c>();
faculty__c fac=new faculty__c();
for(integer i=0;i<=300;i++){
string name='raja';
integer salary=10000;
fac.name=name;
fac.salary__c=salary;

//Add in list
facs.add(fac);
}

//Insert records outside of for loop
try{
insert facs;
}
catch (){
system.debug('Hello');
}

Thanks
Vinita_SFDCVinita_SFDC
Hello,

You will have to work within governor limits. Here you can use list instead of processing one record at a time and move "insert" statement out of For loop. Insert a list out of For loop.

For best practice refer following document:

http://wiki.developerforce.com/page/Apex_Code_Best_Practices

aaryansriaaryansri
Hi Subhash Garhwal

  I tryed ur code it working with out any error but no records are creating in faculty sobject
Subhash GarhwalSubhash Garhwal
than may be some exception will came in your code but you are using catch so it not showing.To get error you can do two things
1. remove try-catch from your code and only use insert statement.
2. update your catch like
catch(exception e) {
System.debug('###### : ' +e);
}
see exception in debug log

Let me know what error you getting if you are not able to slove it.

Thanks

aaryansriaaryansri
Hi subhash

Running the code with out Try and catch. The error message is :-
System.DmlException: Insert failed. First exception on row 0 with id a0E9000000kU8pQEAS; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]


When using catch function as above said .The error message is:-

System.DmlException: Insert failed. First exception on row 0 with id a0E9000000kU8orEAC; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]