[SalesForce] Using single quote by curly braces in String.format in Dynamic SOQL

I'm struggling to use String.format to replace a token with a value when the token is within single quotes:

Example:

String query = String.format('SELECT Id FROM Availability WHERE Person__c = \'{0}\'', personId);

String query is equal to:

SELECT Id FROM Availability WHERE Person__c = {0}

Rather than:

SELECT Id FROM Availability WHERE Person__c = '234567890'

Best Answer

Quoting the merge field makes it literal text. In order to get the merge field to work, you have to quote the quotes:

String query = String.format('SELECT Id FROM Availability WHERE Person__c = \'\'{0}\'\'', personId);

The Apex Code documentation states:

Treat the first argument as a pattern and return a string using the second argument for substitution and formatting in the same manner as apex:outputText and the Java MessageFormat class.

The Java documentation for MessageFormat says:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. A single quote itself must be represented by doubled single quotes '' throughout a String.