我想在 3 个不同的表中执行 3 个插入查询。 但是这三个查询都相互依赖 当第一个查询成功执行时,应该有 第二个查询执行,当第二个查询成功执行时 应该执行第三个查询。
如果有任何服务器错误或任何其他类型的错误发生时 执行第二个查询,则必须从中删除所有记录 由第一个查询插入的数据库。
如果在执行第三个查询时发生错误(成功执行后 第一个和第二个查询)然后必须从数据库中删除所有记录 由第一个和第二个查询插入。
我可以通过在 Catch block 中执行删除查询来实现吗?这是个好主意吗? 或者请给我一个建议,我如何才能做到这一点,因为我在一个 现场项目所以我不能冒任何风险。请尽快回复我。
最佳答案
为您进行的交易。 看这个例子:
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();
}
关于c# - 如果同时执行多个插入查询时发生错误,如何回滚表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21656029/