1. Home
  2. Computing & Technology
  3. Delphi Programming

TAdoConnectionEx - Custom Delphi Component With Source
Preventing Design Time Database Connection

By Zarko Gajic, About.com

The article An Error at Run-Time due to the Database Connection Left Open at Design-Time explains why sometimes live database data at design-time can cause problems at run time.

In short, when the application is started, if the Connected property is left to "True", at design-time, the application will try to connect to the database using the "hard" coded ConnectionString property!

TAdoConnectionEx

Here's the full source code (yes, it is that small) to a custom TADOConnection derived component.

The TAdoConnectionEx is an enhanced ADO connection component that prevents design-time database connections from being used at run-time unless explcitily allowed via the AllowStreamConnected property.

unit ADOConnectionEx;

interface

uses ADODB, Classes;

{
  Enhanced ADO connection component that prevents design-time database connections
  from being used at run-time unless explcitily allowed via the AllowStreamConnected
  property.

  Author: Larry Hengen
}


type
  TADOConnectionEx = class(TADOConnection)
  private
    fAllowStreamConnected: boolean;
  protected
    procedure SetConnected(Value : boolean) ; override;
  published
    property AllowStreamConnected : boolean read fAllowStreamConnected write fAllowStreamConnected;
  end;

procedure Register;

implementation

procedure Register;
begin
  RegisterComponents('delphi.about.com', [TADOConnectionEx]) ;
end;


procedure TADOConnectionEx.SetConnected(Value : boolean) ;
begin
  //if we are not to allow a connection to be established
  //when reading in the form, then
  //toggle it to false when Reading

  if not(FAllowStreamConnected) and (Value) and (csReading in ComponentState) then
    inherited SetConnected(False)
  else
    inherited SetConnected(Value) ;
end;

end.
Basically, the SetConnected method - a protected method that gets called when the public Open method is used.

Installing into the Component palette

The TADoConnectionEx source code above, should be saved in a single unit file (ADOConnectionEx.pas). You'll need to add the component into an existing package. Here's How to Install Custom Component in Delphi (into Existing Package).
Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Using VCL Components
  5. Creating VCL components
  6. TAdoConnectionEx - Prevents Design Time Database Connection - Custom Delphi Component With Source

©2009 About.com, a part of The New York Times Company.

All rights reserved.