Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing SQL command and closing the connection

Tags:

c#

sql

dispose

till now I always used a similar structure to get data from DB and fill a DataTable

public static DataTable GetByID(int testID)
        {
        DataTable table = new DataTable();
        string query = @"SELECT * FROM tbl_Test AS T WHERE T.testID = @testID";

        using (SqlConnection cn = new SqlConnection(Configuration.DefaultConnectionString))
        {
            SqlCommand cmd = new SqlCommand(query, cn);
            cmd.Parameters.Add("@testID", SqlDbType.Int).Value = testID;

            cn.Open();
            table.Load(cmd.ExecuteReader());
        }

        return table;
    }

Now I saw some warnings in the build analysis:

TestService.cs (37): CA2000 : Microsoft.Reliability : In method 'TestService.GetByID(int)', object 'table' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'table' before all references to it are out of scope.

TestService.cs (42): CA2000 : Microsoft.Reliability : In method 'TestService.GetByID(int)', call System.IDisposable.Dispose on object 'cmd' before all references to it are out of scope.

Should I change my code in

    public static DataTable GetByID(int testID)
    {
        DataTable table = new DataTable();
        string query = @"SELECT * FROM tbl_Test AS T WHERE T.testID = @testID";

        using (SqlConnection cn = new SqlConnection(Configuration.DefaultConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand(query, cn))
            {
                cmd.Parameters.Add("@testID", SqlDbType.Int).Value = testID;

                cn.Open();
                table.Load(cmd.ExecuteReader());
            }
        }

        return table;
    }

What to do with DataTable object? Is it a good practice to place SqlCommand inside the using?

Thanks

Cheers

like image 774
MaiOM Avatar asked Dec 12 '11 14:12

MaiOM


People also ask

Does disposing a SQL connection close it?

When you call "Dispose()" on a SqlConnection, internally, it calls "Close()", too. There is no worry - you are free to use Close() manually, or just let Dispose() do it for you. The contract of Dispose is basically that there is an understanding that calling it may render the object unusable for any future operations.

Does dispose close connection?

Net documentation for the OleDbCommand, Close() closes the connection and returns it to the connection pool, and Dispose() closes the connection and REMOVES it from the connection pool.

What does dispose method do with connection object?

Deletes it from the memory.


1 Answers

You should also do this:

using (SqlDataReader reader =
            cmd.ExecuteReader
                (CommandBehavior.CloseConnection))
        {
            table.Load(reader);
        }

when loading the table

like image 123
lnu Avatar answered Nov 08 '22 22:11

lnu