gpt4 book ai didi

c# - 确保所有更新都成功完成?

转载 作者:太空宇宙 更新时间:2023-11-03 21:48:53 25 4
gpt4 key购买 nike

当提交新表单时,我有一些存储过程可以对一些表进行各种更新和插入。它们都是从我的 C# 应用程序中调用的。

现在所有内容都采用try catch 格式,有没有一种方法可以确保在实际将更改提交到数据库之前它们都已成功通过?

假设前 3 个存储过程一切正常,但第 4 个失败,我想反转前 3 个中已经完成的操作。

全有或全无类型的交易。

最佳答案

您需要使用 TransactionScope类(System.Transactions.TransactionScope)

//assuming Table1 has a single INT column, Column1 and has one row with value 12345
//and connectionstring contains a valid connection string to the database.
//this automatically starts a transaction for you
try
{
using (TransactionScope ts = new TransactionScope())
{
//you can open as many connections as you like within the scope although they need to be on the same server. And the transaction scope goes out of scope if control leaves this code.
using (SqlConnection conn = new SqlConnection(connectionstring))
{
conn.Open();
using (SqlCommand comm = new SqlCommand("Insert into Table1(Column1) values(999)")
{
comm.ExecuteNonQuery();
}
using (SqlCommand comm1 = new SqlCommand("DELETE from Table1 where Column1=12345"))
{
comm1.ExecuteNonQuery();
}
}//end using conn
ts.Complete() ; //commit the transaction; Table1 now has 2 rows (12345 and 999)
}//end using ts

}
catch(Exception ex)
{
//Transaction is automatically rolled back for you at this point, Table1 retains original row.
}

关于c# - 确保所有更新都成功完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15533134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com