随笔 - 809  文章 - 0 评论 - 144 阅读 - 770万

总之用事务的宗旨是:

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   del88  阅读(74)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示