总之用事务的宗旨是:

1.不用嵌套事务EnableNested设置为False

2.事务一定要回滚,避免发生异常的情况下,没有回滚 造成,不可估量的错误。

try

frmClientDm.MyMainCon.StartTransaction;

try

   //注意,这里不能有Exit;退出函数,因为退出了,Except部分并没有执行,会造成事务没有回滚

except

  frmClientDm.MyMainCon.Rollback;

end;

 

 

finally

 

end;

 

 

2.用事务一定不要忘记出异常后 回滚事务,避免再次执行 就变成了 嵌套事务,因为上一个事务 虽然有异常,但是 事务已经开启,并没有关闭,如果再次点击按钮 再次调用StartTransaction,就变成了嵌套事务,最好不要用嵌套事务。

 

3.如上图的代码测试如下:

procedure TForm1.正常Click(Sender: TObject);
var
  MyFdq: TFDQuery;
begin
  MyFdq := TFDQuery.Create(nil);
  try
    MyFdq.Connection := FDConnection1;
    FDConnection1.StartTransaction;
    with MyFdq do
    begin
      SQL.Add('insert into top_user(top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
      //SQL.Add('insert into top_user(top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
      //SQL.Add('insert into top_user(top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
      ExecSQL;
    end;
    FDConnection1.Commit;
  finally
    MyFdq.Free;
  end;
end;

procedure TForm1.出错Click(Sender: TObject);
var
  MyFdq: TFDQuery;
begin
  MyFdq := TFDQuery.Create(nil);
  try
    MyFdq.Connection := FDConnection1;
    try
      FDConnection1.StartTransaction;
      with MyFdq do
      begin
        SQL.Add('insert into top_user(2top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
        //SQL.Add('insert into top_user(top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
        //SQL.Add('insert into top_user(top_name,top_pwd,top_open_time) values (''a'',''a'',''1900-01-01 00:00:00'');');
        ExecSQL;
      end;
      FDConnection1.Commit;
    except
      //FDConnection1.Rollback;
    end;

  finally
    MyFdq.Free;
  end;
end;

 

4.事务的正确使用方法:

ADOConnection1.BeginTrans;   //开始事务
try 
with ADOCommand1 do 
begin 
Connection:=ADOConnection1; 
commandtext:='update [country] set [population]=10000 where [name]=''Venezuela''';//正确的SQL语句 
Execute; 
CommandText:='Wrong SQL Command';//错误的SQL 
Execute; 
ADOConnection1.CommitTrans; //提交事务
end; 
except 
on E: Exception do 
begin 
ADOConnection1.RollbackTrans; //如有异常,事务回滚
ShowMessage(E.Message); 
end 
end; 
end;

 

posted on 2014-04-03 20:13  del88  阅读(89)  评论(0)    收藏  举报