Apex
Safe SOQL with bind variables in Apex
Build dynamic SOQL safely with Database.queryWithBinds. Avoids SOQL injection without resorting to String.escapeSingleQuotes everywhere.
// Apex 60+ (Spring '24 GA): Database.queryWithBinds is the recommended
// way to mix dynamic field/object names with user input.
public static List<Account> findByName(String namePart) {
Map<String, Object> binds = new Map<String, Object>{
'pattern' => '%' + namePart + '%'
};
return Database.queryWithBinds(
'SELECT Id, Name FROM Account WHERE Name LIKE :pattern',
binds,
AccessLevel.USER_MODE
);
}Notes
- AccessLevel.USER_MODE enforces FLS + sharing for the running user.
- For static SOQL, prefer the inline binding form (`WHERE Id = :recordId`) over Database.query.