Disposing SQL command and closing the connection Disposing SQL command and closing the connection sql sql

Disposing SQL command and closing the connection


You should also do this:

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

when loading the table


  • The caller of this method should call the dispose of the DataTable returned when it is done using it.
  • Yes, it is a good practice to place SqlCommand inside using.


To "fix" your issue with the DataTable, perhaps you could modify your function.

public static void GetByID(DataTable table, int testID){    // bla bla bla}// calling the functionusing(DataTable table = new DataTable()){    TestService.GetByID(table, 5);}

Not saying this is the optimal solution, but it will solve the complaint.