Search code examples
databasedelphidelphi-7

Overriding AsString in TFields and TStringField


When we swapped database components from ODBC Express to ADO one of the biggest problems we ran into was that ODBC Express "right-trimmed" the results from CHAR fields and ADO didn't.

CHAR fields fill up their entire assigned field length so when we query them with ADO you get a lot of extra spaces.

We have a lot of databases and code that basically depends on the results from the database being trimmed.

Our solution was to edit the delphi source DB.pas and change the getasstring methods from TField and TStringField.

This works but is not a solid solution is there another way to get those results trimmed without changing delphi source code?

When switchting to ADO we decided to not use the TADOQuery class directly but instead we derived our own:

  TOurAdoQuery = class(TADOQuery)
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
    function ExecSQL: Integer;
    procedure Open;
  end;

Solution

  • Descend from TStringField, something like:

    TYourStringField = class(TStringField)
    protected
      function GetAsString: string; override;
    end;
    
    implementation
    function TYourStringField.GetAsString: string;
    begin
      Result := TrimRight(inherited GetAsString);
    end;    
    

    Register your class (you will probably do this in initialization section):

    RegisterClass(TYourStringField);
    

    Put this line where you usually initialize stuff for your application :

    DefaultFieldClasses[ftString] := TYourStringField;
    

    That's it, next time you create dataset all ftString field types will use TYourStringField definition.