Database.query or Database.queryWithBinds methods in the following ways:List<sObject> sobjList = Database.query(string);
List<sObject> sobjList = Database.queryWithBinds(string, bindVariablesMap, accessLevel);
accessLevel parameter allows running the query in user or system mode:Account or MyCustomObject__c) or the generic sObject type. At runtime, Salesforce validates the query result type against the declared variable type, throwing an error if they don't match. This ensures you don't need to cast from a generic sObject to a specific type.String myTestString = 'TestName'; List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE Name = :myTestString');
Database.query:MyCustomObject__c myVariable = new MyCustomObject__c(field1__c ='TestField'); List<sObject> sobjList = Database.query('SELECT Id FROM MyCustomObject__c WHERE field1__c = :myVariable.field1__c'); // Not supported
Database.queryWithBinds to pass bind variables directly from a map:Map<String, Object> acctBinds = new Map<String, Object>{'acctName' => 'Acme Corporation'}; List<Account> accts = Database.queryWithBinds('SELECT Id FROM Account WHERE Name = :acctName', acctBinds, AccessLevel.USER_MODE);
Map Parameter Considerations:
- Map keys are case-sensitive but
queryWithBindstreats them case-insensitively, throwing an error if duplicates exist. - Map keys must adhere to naming standards and avoid reserved keywords.
- Avoid using dot notation with map keys.
escapeSingleQuotes method to sanitize user input:Additional Dynamic SOQL Methods
Database.countQueryandDatabase.countQueryWithBinds: Return the number of records a dynamic SOQL query would return.Database.getQueryLocatorandDatabase.getQueryLocatorWithBinds: Create aQueryLocatorobject for batch Apex or Visualforce.
.png)
Comments
Post a Comment
Please Write your comment here.