ado.net 使用“使用"时关闭连接陈述 [英] ado.net Closing Connection when using "using" statement

查看:23
本文介绍了ado.net 使用“使用"时关闭连接陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样对 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆