1. Computing

TAdoConnectionEx - Custom Delphi Component With Source

Preventing Design Time Database Connection

By

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).

©2014 About.com. All rights reserved.