SOQL Injection can occur in Apex code whenever your application relies on end user input to construct a dynamic SOQL statement and you do not handle the input properly.
To prevent SOQL injection, use the escapeSingleQuotes method. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.
Sample SOQL:
String strText = 'Test';
String SOQL = 'SELECT Id, Name FROM Account WHERE Name = \'' + String.escapeSingleQuotes(strText) + '\'';
List<Account> listAcct = Database.query(SOQL);
system.debug('test ' + listAcct);z