Search code examples
c#sql-serverreturn-valuesqlconnectionsqlcommand

When does SqlCommand close when used in another function?


I have a program in C# where I created various class, and all of them need to make calls to the database. So I decided to create a static class that handles all the calls to allow me to apply far-reaching changes very easily. Within that class I have functions that call the various parts of SqlCommand (ExecuteReader(), etc) I finally got tired of rewriting all the connection code, and abstracted it out to another function called getSqlCommand() which just returns an initialized SqlCommand which I use to perform the various commands. I've chosen to not pass the SqlCommand back to the other programs (though it is a public method in case I need it) because there is some pre-processing if you will that I may do before I had the results back to the program.

My question is, if/when the SqlConnection closes? Since it is being passed back as a return value in a SqlCommand, will it be left open? and if so, can I close it? Here is some code (slightly stripped down) so you can see what I am doing, thanks in advance!

The function to create the SqlCommand:

public static SqlCommand GetSqlCommand(string query)
{
    using (SqlConnection dbConnection = new SqlConnection( SQLConn )) {
        dbConnection.Open();
        SqlCommand cmd = new SqlCommand( query, dbConnection );
        cmd.CommandTimeout = 0;
        return cmd;
    }
}

An example of the usage of the command in the static class:

public static SqlDataReader executeReader( string query )
{
    try {
       return GetSqlCommand(query).ExecuteReader();
    } catch (SqlException) {
       //Notify User and Resolve Error
    }

    return null;
}

Solution

  • A SqlConnection is closed when you call Dispose. Exiting the using block does that. The connection will be closed.

    That's all there is to it. It will not magically stay open because ADO.NET does not know and cannot find out that you returned the connection object.

    Move the connection out of the GetSqlCommand method. Pass the connection object into that method. GetSqlCommand has no business in creating a connection. It should take a connection, use it, but not close it.