我用DBGrid和TQuery控件操作数据库,却发现一个很奇怪的问题,存盘的代码如下try
DbMain.StartTransaction;
query1.first;
while not query1.Eof do
begin
query1.Edit;
query1.FieldByName('f2').asfloat:=query1.fieldbyname('f1').asfloat;
query1.next;
end;
query1.post;
query1.ApplyUpdates;
DbMain.Commit;
query1.CommitUpdates;
Application.MessageBox('存盘成功!','信息提示',MB_OK);
except
DbMain.RollBack;
Application.MessageBox('存盘失败!','信息提示',MB_OK);
end;也就是存盘的时候把Query1中所有记录的f1字段的值赋给f2,当第一次Query1是空的时候,没有问题,程序执行的全部是插入操作,但当插入完毕存盘,再修改Query1中的f1字段后,再次存盘,程序却同时执行了插入和修改的操作,会在数据库中再次插入一条记录,该记录就是未修改前的那条,如果拿掉代码中Query1.first的语句,则没有这个问题,但这样就不能修改所有记录,不符合功能要求了。感觉上似乎是第一次存盘成功后,立刻再执行修改操作程序不能识别到底要插入还是修改了,如何解决这个问题呢?
DbMain.StartTransaction;
query1.first;
while not query1.Eof do
begin
query1.Edit;
query1.FieldByName('f2').asfloat:=query1.fieldbyname('f1').asfloat;
query1.next;
end;
query1.post;
query1.ApplyUpdates;
DbMain.Commit;
query1.CommitUpdates;
Application.MessageBox('存盘成功!','信息提示',MB_OK);
except
DbMain.RollBack;
Application.MessageBox('存盘失败!','信息提示',MB_OK);
end;也就是存盘的时候把Query1中所有记录的f1字段的值赋给f2,当第一次Query1是空的时候,没有问题,程序执行的全部是插入操作,但当插入完毕存盘,再修改Query1中的f1字段后,再次存盘,程序却同时执行了插入和修改的操作,会在数据库中再次插入一条记录,该记录就是未修改前的那条,如果拿掉代码中Query1.first的语句,则没有这个问题,但这样就不能修改所有记录,不符合功能要求了。感觉上似乎是第一次存盘成功后,立刻再执行修改操作程序不能识别到底要插入还是修改了,如何解决这个问题呢?
query1.first;
while not query1.Eof do
begin
query1.Edit;
query1.FieldByName('f2').asfloat:=query1.fieldbyname('f1').asfloat;
query1.next;
end;
query1.post;
query1.ApplyUpdates改为下面这样:with query1 do
if query1.State=dsBrowse then
if query1.RecordCount>0 then
begin
first;
while not query1.Eof do
begin
query1.Edit;
query1.FieldByName('f2').AsFloat:=query1.fieldbyname('f1').AsFloat;
query1.next;
end;
if state=dsEdit then post;
end;试试....别的部分,我没看懂......
if State=dsBrowse then
if RecordCount>0 then
begin
first;
while not Eof do
begin
Edit;
FieldByName('bb').AsString:=fieldbyname('aa').AsString;
next;
end;
if state=dsEdit then post;
end;