gpt4 book ai didi

c# - SQLTransaction.Commit() 是如何工作的?

转载 作者:太空宇宙 更新时间:2023-11-03 23:43:07 24 4
gpt4 key购买 nike

前几天研究了SqlTransaction,知道了SqlTransaction.Commit()的用途——应该是“提交数据库事务”。 -MSDN。

但是它是如何工作的?

例如:我写了一段代码是这样的:

using (SqlTransaction tran = connection.BeginTransaction())
{
try
{
using (SqlCommand cmd = connection.CreateCommand())
{
cmd.CommandText = msg.command;
cmd.Transaction = tran;

cmd.ExecuteNonQuery();
}
}
catch (Exception)
{
// if all of above have any exception, that's mean my transaction is
// failure and my database has no change.
return false;
}

tran.Commit();

// if all of above have no problems, that's mean my transaction is successful
return true;
connection.Dispose();
}

在这种情况下,SQL Server 在另一台计算机上。

我猜:commit 方法有两个周期,周期 1:当我实现 tran.Commit() 时,编译器将向 SQL Server 发出信号并与 SQL Server 对话:“我很好,请help me commit (change) data”,然后SQL Server会执行编译器的请求。第二阶段:当SQL Server 完全执行编译器的请求时,执行结果将返回给我们的编译器。当我们的编译器收到执行结果时,我们的编译器将继续编译下一个命令行(“return true”)。

但是如果在第二个周期,连接断开并且执行结果不会传回我们的编译器。在这种情况下,我们的交易成功与否?数据是否持久化在 SQL Server 中?

附加问题:我对 SQLTransaction.Commit() 的两个周期的预测是否正确?

谢谢!

最佳答案

try
{
using (var conn = new SqlConnection(/* connection string or whatever */))
{
conn.Open();

using (var trans = conn.BeginTransaction())
{
try
{
using (var cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
/* setup command type, text */
/* execute command */
}

trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
/* log exception and the fact that rollback succeeded */
}
}
}
}
catch (Exception ex)
{
/* log or whatever */
}

也阅读这个 https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.commit(v=vs.110).aspx

关于c# - SQLTransaction.Commit() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28359058/

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