0

I have a array of string and its values contains single quotes in it and i need to use this string array in a SOQL query.

for example, consider the string array as EventName and the query is as below,

custom__c resultList = [Select id, Case__c,Type__c,Date_of_Occurrence__c   from custom__c where custom_Name__c IN :escapeQuotes(EventName)]

escapeQuotes function below,

 public static List<String> escapeQuotes(String[] EventName) {
    List<String> newVar = new List<String>();
    for (Integer l = 0 ; l < EventName.size() ; l++ ) {
      newVar.add(String.escapeSingleQuotes(EventName[l]));
    } 
   return newVar;
 }

when there is no single quote in the EventName string array, the query works fine, but when there is a single quote the query give no results.

the same query works in dev console and in work bench adding an escape character in the string. pfb the working query in dev console query editor.

Select id, Case__c,Type__c,Date_of_Occurrence__c   from custom__c where custom_Name__c IN ('test\'s string')

please help

7

You do not need to escape quotes in values that you utilize via Apex bind notation (:), regardless of whether you're using Dynamic or Non-Dynamic SOQL. When you do so, you're actually searching for the literal value of the escaped string, like "my \' string", which isn't likely to match any records.

You need to escape your strings when you use Dynamic SOQL and construct your query as a string, to guard against injection attacks. You also will write a literal escape sequence (\') in any other context where you're writing a literal quoted string and need to escape quotes to prevent prematurely terminating the string literal.

As an example of the first situation, you'd need to do this when using Dynamic SOQL without an Apex bind:

String myQuery = 'SELECT Id FROM Account WHERE Name = \'' + String.escapeSingleQuotes(myParameter) + '\'';
return Database.query(myQuery);

This guards you against SOQL injection attacks. When you use Apex binding, the platform takes responsibility for this security issue.

Not needing to worry about escaping text input is a major benefit of using Apex binding notation.

For more, see SOQL Injection and the excellent Trailhead module Prevent SOQL Injection In Your Code.

|improve this answer|||||
  • +1 @david, is this documented somewhere? – RedDevil Apr 25 '19 at 13:35
  • @RedDevil Thanks for nudging me to include references! I added a couple of links that document how to avoid SOQL injection by using Apex binds. – David Reed Apr 25 '19 at 14:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.