ado.net使用"using"语句时关闭连接

twa*_*wal 31 c# t-sql ado.net

我像这样对SQL Server执行数据库访问方法

  using (SqlConnection con = new SqlConnection(//connection string)
  {
    using (SqlCommand cmd = new SqlCommand(storedProcname, con))
     {
       try{
           con.open();
           //data reader code
       }
       catch
       {

       }
     }
  }
Run Code Online (Sandbox Code Playgroud)

我是否需要关闭或处理SqlCommand,或者using语句是否会为我处理?我只是不希望连接挂开谢谢

Phi*_*unt 57

using会照顾它.在引擎盖下,SqlConnection.Dispose()调用SqlConnection.Close()方法,然后SqlCommand.Dispose()调用SqlCommand.Close().

作为附加背景,using语句是用于try ... finallyIDisposable对象置于其中的语法糖finally.

  • 它将处理它 - 但我仍然会明确地关闭它并使用using()块作为我忘记时的"备份". (3认同)

Dan*_*ant 12

顺便说一句,您可以使代码更简洁和可读,如下所示:

 using (SqlConnection con = new SqlConnection(/*connection string*/))
 using (SqlCommand cmd = new SqlCommand(storedProcname, con))
 {
    //...
 }
Run Code Online (Sandbox Code Playgroud)