lphi中将TMyQuery数据集覆盖到TClientDataS

lphi中将TMyQuery数据集覆盖到TClientDataS

本文介绍了在Delphi中将TMyQuery数据集覆盖到TClientDataSet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我利用devart(corelab)的Mydac组件从Delphi(2006)中访问MySql
很多时候,我需要使用TClientDataSet中的数据
转换数据的最佳方法是什么? TMyQuery的数据集到TClientDataSet
目前,我正在使用

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 TClientDataSetWhat is the best way to convert the dataset of a TMyQuery to TClientDataSetCurrently 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;

是否有更好的方法?

推荐答案

如果您确实确实经常需要此功能,则将其设置为函数,如下所示:

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;

此函数可以在所有地方使用,而不是TClientDataSet.Create(),除非有例外引发您将获得一个开放的TClientDataSet,它拥有并以这种方式释放两个帮助器对象。

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.

(注意:我只将DevArt组件用于MS Sql Server,所以我无法测试。该代码很可能包含错误,但总体思路可行。)

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

这篇关于在Delphi中将TMyQuery数据集覆盖到TClientDataSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 10:24