采取以下代码示例:
string status = "ok";
SqlCommand cmd=null;
SqlTransaction trans=null;
try
{
cmd = defs.prepquery("");
trans = cmd.Connection.BeginTransaction();
cmd.Transaction = trans;
}
catch (Exception ex)
{
status = defs.logerror("initalizing sql transaction:" + ex.ToString());
return status;
}
try
{
if (oper == "submit")
{
cmd.CommandText = "update DCM_Mapping_Sessions set StatusID=2 " +
"where MappingSessionID=" + mpsid + "";
cmd.ExecuteNonQuery();
}
else if (oper == "delete")
{
// .......etc etc
}
catch(Exception ex2)
{
//rollback , close the connection
// handle the ex
}
// if everything is ok , comit the transaction and close the connection
}
所以我的问题是:发生异常时,try块中的对象会发生什么?
如果发生异常,C#是否可以让我变得懒惰并销毁对象(销毁待处理的事务,意味着回滚)并关闭连接?
我来自C \ C++背景,因此为了安全起见,我正在做上述事情,并且如果下面发生异常,则不会以打开事务结束。
最佳答案
您应该处置/关闭连接和事务。
最好的方法是将创建内容包装在 using
statement中。
Provides a convenient syntax that ensures the correct use of IDisposable objects.
本质上,
using
语句将对象的创建包装在 try{}finally{}
块中,以确保正确处理。 using(var cmd = defs.prepquery(""))
using(var trans = cmd.Connection.BeginTransaction())
{
}
关于c# - try catch block 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671456/