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
Hari nadh babu EluruHari nadh babu Eluru 

records were not updated

Hi all,
At in batch apex coding, they want to update the records in Student__c custom sobject as like if student is male they can appear Mr infront of his name. If student is female they can appear Miss infront of her name

I tried this above code:
public class apex_student implements database.batchable<sobject>{
    integer count = 0;
    
    public database.querylocator start(database.batchableContext abc){
        string myacc = 'SELECT Student_Id__c, Name, Gender__c FROM Student__c';
        system.debug('start:::');
        return database.getquerylocator(myacc);
    }
    
    public void execute(database.batchableContext abc, list<Student__c> acc){
        count++;
        system.debug('Execute'+count);
            
        for(Student__c x:acc){
            if(x.Gender__c == 'Male'){
                x.Gender__c = 'Mr';
            }
            
            if(x.Gender__c == 'Female'){
                x.Gender__c = 'Miss';
                update x;
            }
        }
    }
    
    public void finish(database.batchableContext abc){
        system.debug('Finish:::');
    }
}
But records in sobject was not updated, Please resolve my problem. Thank You !
 
Best Answer chosen by Hari nadh babu Eluru
AbhinavAbhinav (Salesforce Developers) 
Add a list to update record
public void execute(database.batchableContext abc, list<Student__c> acc){
        count++;
        system.debug('Execute'+count);
    List<Student__c> listToUpdate = new List<Student__c >();      
        for(Student__c x:acc){
            if(x.Gender__c == 'Male'){
                x.Gender__c = 'Mr';
              listToUpdate.add(x);
            }
            
            if(x.Gender__c == 'Female'){
                x.Gender__c = 'Miss';
                listToUpdate.add(x);
            }
        }
Update listToUpdate;
    }