delphi手动创建dataset并插入值

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs,DB,DBClient, Vcl.Grids, Vcl.DBGrids;

type
  TForm1 = class(TForm)
    dbgrd1: TDBGrid;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  class function AddDataToSet(AdsData: TDataSet): TDataSet;
  class function CreateDataSet(dsTemp:TDataSet): TDataSet;
  end;

var
  Form1: TForm1;

implementation


//创建dataset
class function TForm1.CreateDataSet(dsTemp:TDataSet): TDataSet;
var
cdsTemp: TClientDataSet;
begin
try
    //创建DataSet
    cdsTemp := TClientDataSet.Create(Application);
    if dsTemp.FieldDefs <> nil then
    begin
      cdsTemp.FieldDefs.Assign(dsTemp.FieldDefs);
      cdsTemp.CreateDataSet;
      result := (cdsTemp as TDataSet);
    end;
finally
    //内存释放
    dsTemp.Free;
end;
end;


class function TForm1.AddDataToSet(AdsData: TDataSet): TDataSet;
var
intLoop:Integer;
begin
//打开数据集
AdsData.Open;
with AdsData do
begin
    for intLoop := 0 to 10 do
    begin
      Append;//添加
      FieldByName('Code').AsString := 'Code' + intToStr(intLoop);
      FieldByName('Name').AsString := 'Name' + intToStr(intLoop);
      FieldByName('Code').AsInteger := intLoop;
      post;//提交
    end;
end;
end;
{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
dsTemp:TDataSet;
begin
   //初始化
   dsTemp := TDataSet.Create(Application);
   with dsTemp.FieldDefs do
    begin
      Add('code',ftString,8);
      Add('name',ftString,20);
      Add('Number',ftInteger);
    end;
   dsTemp:=TForm1.CreateDataSet(dsTemp);
   TForm1.AddDataToSet(dsTemp);

  dsTemp.Open;
  while not dsTemp.Eof do
  begin
    showmessage(string(dsTemp.FieldByName('Name').Value)) ;
    dsTemp.Next ;
  end ;

end;

end.

DataSet有两个东西,一个是表结构FieldDefs,一个是TClientDataSet。这个.net还是有一些不同。

原文地址:https://www.cnblogs.com/hougelou/p/3958718.html