【问题标题】:how to rollback table if any error occur while executing multiple insert query simultaneously如果同时执行多个插入查询时发生任何错误,如何回滚表
【发布时间】:2014-02-09 06:13:58
【问题描述】:

我想在 3 个不同的表中执行 3 个插入查询。 但是这三个查询都是相互依赖的 当第一个查询成功执行时,应该有 第二个查询执行,当第二个查询成功执行时 应该执行第三个查询。

如果有任何服务器错误或任何其他类型的错误发生,同时 执行第二个查询,那么它必须删除所有记录 由第一个查询插入的数据库。

如果在执行第三次查询时发生错误(成功执行后 第一个和第二个查询)然后必须从数据库中删除所有记录 由第一个和第二个查询插入。

我可以通过在 Catch Block 中执行删除查询来实现这一点吗?这是个好主意吗? 或者请给我一个建议,因为我在一个 现场项目,所以我不能冒任何风险。请尽快回复我。

【问题讨论】:

  • 阅读交易,你会找到所有的答案
  • 是的。那是“已经知道完全简单的选择并且现在应该阅读数据库是什么的基础知识的初学者的数据库”。交易到recue。

标签: c# asp.net sql-server


【解决方案1】:

为您进行的交易。 看看这个例子:

    SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Northwind;uid=sa;pwd=sa;");
  myConnection.Open();

  // Start a local transaction
  SqlTransaction myTrans = myConnection.BeginTransaction();

  SqlCommand myCommand = new SqlCommand();
  myCommand.Connection = myConnection;
  myCommand.Transaction = myTrans;
  try
  {
    myCommand.CommandText = "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
    myCommand.ExecuteNonQuery();
    myCommand.CommandText = "delete * from Region where RegionID=101";

    // Attempt to commit the transaction. 
    myCommand.ExecuteNonQuery();
    myTrans.Commit();
    Response.Write("Both records are written to database.");
  }
  catch (Exception ep)
  {
    // Attempt to roll back the transaction. 
    myTrans.Rollback();
    Response.Write(ep.ToString());
    Response.Write("Neither record was written to database.");
  }
  finally
  {
    myConnection.Close();
  }

【讨论】:

  • 没关系。我也不会使用 dispose 调用。我会使用 - using 语句;)这完全可以让代码演示一个概念。
猜你喜欢
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 2014-12-08
  • 2015-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多