NoviceToDotNet
NoviceToDotNet

Reputation: 10805

What is using connection in the code

What is the purpose of using (connection) in the code - please explain me

static void HasRows(SqlConnection connection)
{
    using (connection)/// what is this line 
    {
        SqlCommand command = new SqlCommand(
          "SELECT CategoryID, CategoryName FROM Categories;",
          connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        if (reader.HasRows)
        {
            while (reader.Read())
            {
                Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                    reader.GetString(1));
            }
        }
        else
        {
            Console.WriteLine("No rows found.");
        }
        reader.Close();
    }
}

Upvotes: 2

Views: 2818

Answers (3)

Nam Le
Nam Le

Reputation: 1136

using (connection){
    connection.Open();
}

makes sure that connection is closed when the application is done using it. similar to a Try Catch.

try{
    connection.Open();
}
catch{
}
finally{
    connection.Dispose(); 
}

Disposing of the connection is another way of saying closing a connection. An open connection can leak memory and if you have too many it can slow down or freeze up whatever you are connecting to.

the using function closes the connection even after you return something from the class you are in. same as the try catch. it always closes the connection no matter what happens inside the brackets. even if there is an exception that breaks out of the class/application the connection still gets closed

Upvotes: 6

Zephyr
Zephyr

Reputation: 7823

I would probably re-write the method to something like the following:

static void HasRows(string connectionString)
{
    using (var connection = new SqlConnection(connectionString))
    using(var command = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",
        connection))
    {
        connection.Open();

        using (var reader = command.ExecuteReader())
        {
            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("{0}\t{1}", reader.GetInt32(0),
                        reader.GetString(1));
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }
        }
    }
}

In your original implementation the caller could be at the receiving end of an ObjectDisposedException exception, because the SqlConnection is passed in as a parameter.

Upvotes: 2

Neil Knight
Neil Knight

Reputation: 48547

Using

Quote from site:

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

Upvotes: 5

Related Questions