ESC function
MySQL String routines
Return to Introduction  Previous page  Next page
Unit
acUtils  

Declaration
function ESC(const Str: String): String;  

Description
The ESC function "escapes" the string, makes the string safe for call as SQL string parameter. It adds the slash character before all quotes and doublequotes, converts #13 character to \r and #10 to \n.  

Original code
function ESC(const Str: String): String;  
var  
  I, RI: Integer;  
 
  procedure AddToResult(Ch: Char);  
  begin  
    Result[RI] := '\';  
    inc(RI);  
    Result[RI] := Ch;  
    inc(RI);  
  end;  
 
begin  
  SetLength(Result, Length(Str) shl 1 + 3); // (length of original string) * 2 + 1  
  Result[1] := '''';  
  RI := 2;  
 
  for I := 1 to Length(Str) do  
    case Str[I] of  
      #0:   AddToResult('0');  
      #13:  AddToResult('r');  
      #10:  AddToResult('n');  
      '\''''''"': AddToResult(Str[I]);  
      else  
        Result[RI] := Str[I];  
        Inc(RI);  
     end;  
 
  Result[RI] := '''';  
  SetLength(Result, RI);  
end;