Question

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 ?

Was it helpful?

Solution

If you really do need this very often, then make it a function, like so:

function CreateAndOpenClientDataset(AOwner: TComponent;
  AConnection: TConnection; ACommand: string): TClientDataSet;
var
  MyQuery: TMyQuery;
  Dsp: TDataSetProvider;
begin
  Result := TClientDataSet.Create(AOwner);
  try
    MyQuery := TMyQuery.Create(Result);
    MyQuery.Connection := AConnection;
    MyQuery.SQL.Text := ACommand;

    Dsp := TDataSetProvider.Create(Result);
    Dsp.DataSet := MyQuery;

    Result.SetProvider(Dsp);
    Result.Open;
  except
    Result.Free;
    raise;
  end;
end;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top