[SalesForce] Accessing the fields of Database.query() results

Database.query(query) returns sobjects.

I want to access each fields in this sobject to check the value on each field.

How is this done in controller?

Best Answer

Since Database.query returns a List<SObject> you'll want to cast the result before you use it to access any fields. Once you've done that you can access the fields like you normally would.

List<Account> accounts = (List<Account>)Database.query(...);

// You can do the cast directly in the loop declaration, but I've not done so here for clarity
for(Account a : accounts)
{
    // Do something with your Accounts
}

You can access the fields without casting by using get(String) and getSObject(Schema.SObjectField), but I wouldn't recommend using them unless you need the dynamic behaviour. By using the dynamic methods you lose all the type-safety features that Force.com provides.

Related Topic