为什么使用using语句用的SqlTransaction? [英] Why use a using statement with a SqlTransaction?
问题描述
我已经运行到一些问题有关,我用我的code一的SqlTransaction。在我的谷歌搜索我看到使用using语句用的SqlTransaction许多人。
I've been running into some problems concerning a SqlTransaction I'm using in my code. During my Googling I see many people using a using statement with a SqlTransaction.
什么是利益和/或使用这种类型的语句用的SqlTransaction的区别?
What is the benefit and/or difference of using this type of statement with a SqlTransaction?
using (SqlConnection cn = new SqlConnection())
{
using (SqlTransaction tr = cn.BeginTransaction())
{
//some code
tr.Commit();
}
}
目前我的code是这样的:
Currently my code looks like this:
SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"]);
cn.Open();
SqlTransaction tr = cn.BeginTransaction();
try
{
//some code
tr.Commit();
cn.Close();
}
catch(Exception ex)
{
tr.Rollback();
cn.Close();
throw ex;
}
什么是比其他的一种方式?
What is the advantage of one way over the other?
推荐答案
A 使用
语句应使用每次创建一个类的实例,它实现的IDisposable
的块范围内的的。它确保了的Dispose()
方法将被调用该实例,一个异常是否抛出。
A using
statement should be used every time you create an instance of a class that implements IDisposable
within the scope of a block. It ensures that the Dispose()
method will be called on that instance, whether or not an exception is thrown.
在特定的,你的code只能转换托管异常,然后抛出一个新的异常,而不是重新抛出现有销毁堆栈帧。
In particular, your code only catches managed exceptions, then destroys the stack frame by throwing a new exception instead of rethrowing the existing one.
做正确的做法是:
using (SqlConnection cn = new SqlConnection(ConfigurationManager.AppSettings["T3"])) {
cn.Open();
using (SqlTransaction tr = cn.BeginTransaction()) {
//some code
tr.Commit();
}
}
请注意,如果你的类有实现的IDisposable
类型的实例成员,那么你的类必须实现的IDisposable
本身,并在自己的的Dispose()
调用这些成员的处理。
Note that if your class has instance members of types that implement IDisposable
, then your class must implement IDisposable
itself, and dispose of those members during its own Dispose()
call.
这篇关于为什么使用using语句用的SqlTransaction?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!