ado.net Closing Connection when using “using” statement

后端 未结 7 625
青春惊慌失措
青春惊慌失措 2020-11-27 07:46

I am doing my database access methods to SQL Server like this

  using (SqlConnection con = new SqlConnection(//connection string)
  {
    using (SqlCommand c         


        
相关标签:
7条回答
  • 2020-11-27 07:52

    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

    0 讨论(0)
  • 2020-11-27 08:01

    when the scope

    using (SqlConnection con = new SqlConnection(//connection string) 
    {
    }
    

    will over , connection will automatically be disposed by runtime. so don't worry

    0 讨论(0)
  • 2020-11-27 08:02

    As an aside, you can make the code more concise and readable as follows:

     using (SqlConnection con = new SqlConnection(/*connection string*/))
     using (SqlCommand cmd = new SqlCommand(storedProcname, con))
     {
        //...
     }
    
    0 讨论(0)
  • 2020-11-27 08:02

    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.

    0 讨论(0)
  • 2020-11-27 08:14

    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.

    0 讨论(0)
  • 2020-11-27 08:17

    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().

    As additional background, a using statement is syntactic sugar for a try ... finally that disposes the IDisposable object in the finally.

    0 讨论(0)
提交回复
热议问题