0

Again I have a problem with the TClientDataSet. I guess it's something really simple but I struggle on it for a while now.

Here's some code what shows what I want to do:

procedure TForm1.Button1Click(Sender: TObject);
begin
  ClientDataSet1.Insert;
  ClientDataSet1.FieldByName('anruf_von').AsDateTime := time;
  ClientDataSet1.Post;
  ClientDataSet1.ApplyUpdates(0); // without this applyUpdates in button2 works. 
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  ClientDataSet1.edit;
  ClientDataSet1.FieldByName('anruf_bis').AsDateTime := time;
  ClientDataSet1.Post;
  showmessage(intToStr(ClientDataSet1.ChangeCount)); // returns 1
  if ClientDataSet1.ChangeCount > 0 then
    ClientDataSet1.applyUpdates(0);
end;

The code is self explaining I think. When I press button1, a record is created and after the call to applyUpdates its written to the databse. When I press button2, I want to make a change to this record and apply the updates to the database - and that doesn't work. But when I comment out the applyUpdates in button1, the applyUpdates in button2 works correctly.

doubleu
  • 119
  • 3
  • 10
  • Doesn't work? What do you mean by that? – Ondrej Kelle Jul 02 '10 at 11:01
  • I mean the updates are not written to the database table. – doubleu Jul 02 '10 at 11:12
  • In that case I would check the server side to see what SQL is used by the provider. Or maybe the first call (Insert) doesn't return the value of the primary key field (e.g. if it's auto-generated by the server) and that's why update fails? – Ondrej Kelle Jul 02 '10 at 11:18
  • Just guessing: in order to update the new inserted record, the ClientDataSet needs to be refreshed first. Do you have an event handler for OnReconcileError and OnPostError defined? – mjn Jul 02 '10 at 12:02

1 Answers1

1

Try to change Provider.UpdateMode to upWhereKeyOnly, and set key field in Provider.OnUpdateData.

My gues is that insert works always since it is executed as

 INSERT INTO ATABLE (anruf_von, anruf_bis) VALUES (...)

But update fails, since WHERE part will match DB stored time with time from clientdataset. In fact, you will probably try to match two doubles, which is a no-no.

 UPDATE ATABLE SET anruf_bis=<Time> 
 WHERE anruf_von=<WRONG Time, with more precision than stored in db>

When you set UpdateMode to upWhereKeyOnly, generated SQL sholud look like this

 UPDATE ATABLE SET anruf_bis=<Time> 
 WHERE ID=<ID Value>
dmajkic
  • 3,448
  • 1
  • 18
  • 24