ado.net 使用“using”时关闭连接陈述
我正在像这样对 SQL Server 进行数据库访问方法,
using (SqlConnection con = new SqlConnection(//connection string)
{
using (SqlCommand cmd = new SqlCommand(storedProcname, con))
{
try{
con.open();
//data reader code
}
catch
{
}
}
}
我是否需要关闭或处置 SqlCommand,还是 using 语句会为我处理这个问题?我只是不想让连接保持打开状态 谢谢
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
{
}
}
}
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
using
将为您处理好它。在底层,SqlConnection.Dispose()
调用SqlConnection.Close()
方法,SqlCommand.Dispose()
调用SqlCommand .Close()
。作为附加背景,
using
语句是try ...finally
的语法糖,它在finally< 中处置
IDisposable
对象。 /代码>。The
using
will take care of it for you. Under the hood,SqlConnection.Dispose()
calls theSqlConnection.Close()
method, andSqlCommand.Dispose()
callsSqlCommand.Close()
.As additional background, a
using
statement is syntactic sugar for atry ... finally
that disposes theIDisposable
object in thefinally
.顺便说一句,您可以使代码更加简洁和可读,如下所示:
As an aside, you can make the code more concise and readable as follows:
正如 Phil 所说,using 子句会为你解决这个问题。编译时,它将连接创建包装在 try ..finally 中,并将连接处置调用放在 finally 中。
有关详细信息,您可以参阅 msdn 上的 using statements 文章。
As Phil said, the using clause will take care of it for you. When compiled down it wraps the connection create in a try .. finally and places the connection disposal call inside the finally.
For more information you can see the using statement article at msdn.
是的,您的代码将关闭连接,但这通常意味着释放回连接池以便稍后真正关闭。
如果您执行这段代码,然后执行 sp_who 并观察到您的连接仍然存在,这就是原因。
如果您绝对需要真正关闭连接(当然是一种边缘情况),请使用ClearAllPools
SqlConnection 的静态方法
Yes your code will close the connection, however that typcally means release back to the connection pool to be truely closed later.
If you execute this snippet of code, and then do an sp_who and observe that your connection is still there, that would be why.
If you absolutely need the connection truely closed (an edge case to be sure) then use the ClearAllPools
static method of ths SqlConnection
Using
关键字会自动为您关闭连接所以你不需要担心每次最后都会调用
connection.close()
。Using
keyword will automatically close the connection for youso you don't need to worry about calling
connection.close()
at the end every time.当范围
结束时,连接将由运行时自动释放。所以不用担心
when the scope
will over , connection will automatically be disposed by runtime. so don't worry
我认为 SqlCommand 不需要“使用”。 “使用”SqlConnection 就可以为您完成这项工作。
事实上,您的连接已提交到连接池。
I think "using" was not required for SqlCommand. "Using" for SqlConnection would have done the job for you alone.
In fact you connection is submitted to Connection pool.