ado.net 使用“使用"时关闭连接陈述 [英] ado.net Closing Connection when using "using" statement
问题描述
我正在像这样对 SQL Server 执行我的数据库访问方法
I am doing my database access methods to SQL Server like this
using (SqlConnection con = new SqlConnection(//connection string)
{
using (SqlCommand cmd = new SqlCommand(storedProcname, con))
{
try{
con.open();
//data reader code
}
catch
{
}
}
}
我是否需要关闭或处理 SqlCommand,或者 using 语句会为我处理这些吗?我只是不想连接挂起谢谢
Do I need to be closing or disposing of SqlCommand, or will the using statement take care of that for me? I just don't want connection hanging open Thanks
推荐答案
using
会为您处理.在幕后,SqlConnection.Dispose()
调用 SqlConnection.Close()
方法,SqlCommand.Dispose()
调用 SqlCommand.Close()
.
The using
will take care of it for you. Under the hood, SqlConnection.Dispose()
calls the SqlConnection.Close()
method, and SqlCommand.Dispose()
calls SqlCommand.Close()
.
作为附加背景,using
语句是 try ... finally
的语法糖,它在 IDisposable
对象中处理 >最后
.
As additional background, a using
statement is syntactic sugar for a try ... finally
that disposes the IDisposable
object in the finally
.
这篇关于ado.net 使用“使用"时关闭连接陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!