Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do we need using for the SqlCommand or is it enough just for the SqlConnection and SqlDataReader

Tags:

c#

ado.net

i took this code from msdn

string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";

    using (SqlConnection conn = new SqlConnection(connString))
    {
      SqlCommand cmd = conn.CreateCommand();
      cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";

      conn.Open();

      using (SqlDataReader dr = cmd.ExecuteReader())
      {
        while (dr.Read())
          Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
      }
    }

as you can see there is no using for the SqlCommand here, so, does it needs to be ?

like image 279
Omu Avatar asked Feb 12 '10 13:02

Omu


People also ask

Do I need to dispose SqlCommand?

"Not calling dispose on the command won't do anything too bad." True, but don't get used to it; it's only true for SqlCommand s. On the other hand, not disposing a SqlCeCommand , for example, will cause your mobile device to run out of memory quite fast.

Why do we use SqlCommand?

SQL stands for Structured Query Language. SQL commands are the instructions used to communicate with a database to perform tasks, functions, and queries with data. SQL commands can be used to search the database and to do other functions like creating tables, adding data to tables, modifying data, and dropping tables.

Is it necessary to manually close and dispose of SqlDataReader?

You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.

Why do we need SqlCommand in C#?

SqlCommand in C# allow the user to query and send the commands to the database. SQL command is specified by the SQL connection object. Two methods are used, ExecuteReader method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is the method that is best for the different commands.


1 Answers

You need a using for every object you create that implements IDisposable. That includes the SqlCommand and the SqlConnection.


There are very few exceptions to this rule. The main exception is WCF client proxies. Due to a design flaw, their Dispose method can sometimes throw an exception. If you used the proxy in a using statement, this second exception would cause you to lose the original exception.

like image 119
John Saunders Avatar answered Sep 28 '22 08:09

John Saunders