Search code examples
delphidelphi-xe2sybasetclientdatasettcxgrid

Copying Clientdataset records to Database table


What I'm trying to achieve to to insert/copy records from a tClientDataSet to a database table(Database is Sybase ASA).

I also have a form with a cxgrid on it which I can see the records from the cds, so I know there are records in it.

At the click of a button I do the following:

with dmData.cds do
  begin
    Close;
    Open;
    First;
    while not (EOF) do
    begin
      dmData.qry1.Open;
      dmData.qry1.Insert;
      dmData.qry1.FieldByName('field1').AsString := dmData.cds.FieldByName('field1').AsString;
      dmData.qry1.FieldByName('field2').AsString := dmData.cds.FieldByName('field2').AsString;
      dmData.qry1.FieldByName('field3').AsString := dmData.cds.FieldByName('field3').AsString;
      dmData.qry1.Post;
      Next;
    end;
  end;

I don't get any errors after this is done but when looking in the database table there are no records inserted.

I don't know what I'm doing wrong, any help would be much appreciated.


Solution

  • It seems you are trying to do the work that TClientDataSet does for you. In order to have all this working you need three components:

    1. An instance of a dataset able to talk to your data server, already configured to do so
    2. An instance of TDatasetProvider referencing the previous dataset, by using the Dataset property
    3. An instance of TClientDataSet referencing the previous provider, by using the ProviderName property

    After all the records in TClientDataset (CDS) were updated, you call ApplyUpdates(0) to send them to the provider. When you call this method, the CDS builds a data pack named Delta with the records that have to be persisted and send it to the provider.

    The provider does not know how to persist the records existing in the Delta, so it coworks with the dataset you assigned to it. For each record in the Delta, the corresponding operation is executed over the dataset, so the data server will start receiving commands.

    At the end, the provider notifies the CDS that everything was alright (this is named reconciliation), eventually returning keys generated during the insert operations. Those keys will appear in the CDS.

    After all that, the status of the changed records will be cleared, in order to report no pending changes (an important something that your code was not doing).

    I recomend you read more about DataSnap to really master it. The Delphi help has enough information on that.