Search code examples
mysqldelphidatasetfreepascalzeos

TDataset and TMemDataset


I need to iterate through a number of MySQL queries and save them in an array of TMemDataset's. This seems to do it:

MemDataset1.CopyFromDataset(ZQuery1,True); 

However each time the query changes, all the previous TMemDataset's are changed to contain the new values (I guess because they are "data-aware components"). If I get rid of ZQuery1 with ZQuery1.Free, then all of the data vanishes. How do I avoid this?

I am using FreePascal, but I bet the solution for Delphi would apply too.


Solution

  • The solution is to have an array of ZQuery as well as an array of MemDataSet

    type
      TZQueries = array of TZQuery;
      TMemDataSets = array of TMemDataset;
    
    procedure Test;
    var
      ZQueries: TZQueries;
      MemDatasets: TMemDatasets;
      i: integer;
    begin
      try
        SetLength(ZQueries,10);
        SetLength(MemDatasets,10);
        for i:= Low(ZQueries) to high(ZQueries) do begin
          ZQueries[i]:= TZQuery.Create;
          ZQueries[i].Connection:= ZConnection1;
          ZQueries[i].SQL.Text:= QueryTextFromSomewhere
        end; {for i} 
        for i:= Low(MemDatasets) to High(MemDatasets) do begin
          MemDatasets[i]:= TMemDataset.Create;
          ZQueries[i].Open;
          MemDatasets[i].CopyFromDataset(ZQueries[i],True);
        end; {for i}
        ....
          code to process the memdatasets
        ....
      finally
        for i = Low(ZQueries) to High(ZQueries) do begin
          ZQueries[i].Free;
        end; {for i}
        for i = Low(MemDatasets) to High(MemDatasets) do begin
          MemDatasets[i].Free;
        end; {for i}
      end; {tryf}
    end;
    

    Something like that should work, because now there's no more confusion between the Queries and the memdatasets.