Working with Associated Datasets

From RAD Studio
Jump to: navigation, search

Go Up to Connecting to Databases Index


All database connection components maintain a list of all datasets that use them to connect to a database. A connection component uses this list, for example, to close all of the datasets when it closes the database connection.

You can use this list as well, to perform actions on all the datasets that use a specific connection component to connect to a particular database.

Closing all datasets without disconnecting from the server

The connection component automatically closes all datasets when you close its connection. There may be times, however, when you want to close all datasets without disconnecting from the database server.

To close all open datasets without disconnecting from a server, you can use the CloseDataSets method.

For TADOConnection and TIBDatabase, calling CloseDataSets always leaves the connection open. For TDatabase and TSQLConnection, you must also set the KeepConnection property to True.

Iterating through the associated datasets

To perform any actions (other than closing them all) on all the datasets that use a connection component, use the DataSets and DataSetCount properties. DataSets is an indexed array of all datasets that are linked to the connection component. For all connection components except TADOConnection, this list includes only the active datasets. TADOConnection lists the inactive datasets as well. DataSetCount is the number of datasets in this array.

Note: When you use a specialized client dataset to cache updates (as opposed to the generic client dataset, TClientDataSet), the DataSets property lists the internal dataset owned by the client dataset, not the client dataset itself.

You can use DataSets with DataSetCount to cycle through all currently active datasets in code. For example, the following code cycles through all active datasets and disables any controls that use the data they provide:

 var
   I: Integer;
 begin
   with MyDBConnection do
   begin
     for I := 0 to DataSetCount - 1 do
       DataSets[I].DisableControls;
   end;
 end;

Note: TADOConnection supports command objects as well as datasets. You can iterate through these much like you iterate through the datasets, by using the Commands and CommandCount properties.

See Also