2

I have a Java class where I construct SOQL queries using String concatenation.

Is there any best practice which someone can suggest to escape SOQL special characters like single quotes?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
vivek_ganesan
  • 658
  • 4
  • 19
  • well, there is String.escapeSingleQuotes() method for that. ex: c.lastname=String.escapeSingleQuotes(c.lastname); Similar Question: http://salesforce.stackexchange.com/questions/8505/how-to-use-the-escapesinglequotes-method – Shailendra Patel Apr 28 '15 at 05:21
  • 1
    @ShailendraPatel I am looking for a Java code where the post talks about Salesforce Apex code. – vivek_ganesan Apr 28 '15 at 06:14

1 Answers1

-1

I am sorry, I misunderstood the problem, My bad.

Here is the solution:

1.Use prepared Statement.

String data="a'b";
String stmt = " INSERT INTO student (column_name) VALUES (?)";
PreparedStatement statement= con.prepareStatement(stmt);
statement.setString(1,data);
statement.executeUpdate();

2.Escape the single quotes. Single quotes can be escaped by using double single quotes. ' --> ''

String data="a'b";
String changedUserString = userString.replace("'","''");
String insertTableSQL = "INSERT INTO student (column_name) VALUES("
                        +" '"+data+"' )";
  • Are you sure this is SOQL? Salesforce Object Query Language? – vivek_ganesan Apr 28 '15 at 07:30
  • Either use String.escapeSingleQuotes method or backspace: \'Hello\' . – Shailendra Patel Apr 28 '15 at 20:49
  • 1
    @ShailendraPatel, the OP is using Java bindings for Salesforce, and probably passing an SOQL string into the 'query' method of the Salesforce Enterprise wsdl. I'm trying a similar thing. I haven't come across any way of performing escaping on the Java side - I don't think the String.escapeSingleQuotes method is available to Java developers. I'm expecting to have to write my own escaping method based on documentation here http://www.salesforce.com/us/developer/docs/soql_sosl/Content/sforce_api_calls_soql_select_quotedstringescapes.htm – simonh May 27 '15 at 11:12