I make use of the Mydac components by devart (corelab) to access MySql from Delphi (2006) Very often I need to work with data in a TClientDataSet What is the best way to convert the dataset of a TMyQuery to TClientDataSet Currently I am using
var
MyQuery : TMyQuery;
Dsp : TDataSetProvider;
Cds : TClientDataSet;
begin
MyQuery := nil;
Dsp := nil;
Cds := nil;
try
MyQuery := TMyQuery.Create(nil);
Dsp := TDataSetProvider.Create(nil);
Cds := TClientDataSet.Create(nil);
MyQuery.Connection := TheConnection;
MyQuery.SQL.Text := CmdStr;
Dsp.DataSet := MyQuery;
Cds.SetProvider(Dsp);
Cds.Open;
////////////////////////////////////////////////////////////////////////
/// MAKE USES OF THE CDS //
////////////////////////////////////////////////////////////////////////
finally
FreeAndNil(Cds);
FreeAndNil(Dsp);
FreeAndNil(MyQuery);
end;
end;
Is there a better way of doing this ?
If you really do need this very often, then make it a function, like so:
This function you can use in all places instead of TClientDataSet.Create(), and unless an exception is raised you will be given an open TClientDataSet which owns and that way also frees the two helper objects.
(Note: I only use the DevArt components for MS Sql Server, so I can't test. The code may well contain errors, but the general idea works.)