Search code examples
c#sqlconnectionusing

C# Using SQL Method needs a close-method?


When using a using block for SQL connections in C#, does this also a close method? I'm asking as I need to explicitly use the con.Open() method. I found this example:

using (SqlConnection con = new SqlConnection(connectionString))
{
   con.Open(); // open method

   string queryString = "select * from db";
   SqlCommand cmd = new SqlCommand(queryString, con);
   SqlDataReader reader = cmd.ExecuteReader();
   reader.Read();

   ???         // What about a close method?
}

Or does the using block close the connection itself?


Solution

  • using translates to:

    SqlConnection con = new SqlConnection(connectionString)
    try
    {
       con.Open(); <-- open method
    
       string queryString = "select * from db";
       SqlCommand cmd = new SqlCommand(queryString, con);
       SqlDataReader reader = cmd.ExecuteReader();
       reader.Read();
    }
    finally
    {
        if (con!= null)
            ((IDisposable)con).Dispose();
    }
    

    where ((IDisposable)con.Dispose(); closes what is to be closed.