Solved

SqlConnection

Posted on 2011-03-07
2
312 Views
Last Modified: 2012-05-11
Pls see code attached.
Do I need to write cnn.Close() and  cnn.Dispose() statements in that code or the statement
using (var cnn = new SqlConnection(MyConnection)){}

Open in new window

takes care of it automatically?

Thanks.
using (var cnn = new SqlConnection(MyConnection))
        {
            using (var cmd = new SqlCommand("[mySchema].[UpdateComments]", cnn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@comment", comment);
               cnn.Open();
                cmd.ExecuteNonQuery();
            }
            cnn.Close();
            cnn.Dispose();
        }

Open in new window

0
Comment
Question by:patd1
  • 2
2 Comments
 
LVL 11

Accepted Solution

by:
lenordiste earned 500 total points
ID: 35063111
"using" will call dispose on your SqlConnection object and thus close the connection. You don't need to write cnn.Close() or cnn.Dispose()
0
 
LVL 11

Assisted Solution

by:lenordiste
lenordiste earned 500 total points
ID: 35063124
i would rewrite your code like so:
using (var cnn = new SqlConnection(MyConnection))
        {
            using (var cmd = new SqlCommand("[mySchema].[UpdateComments]", cnn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@comment", comment);
               cnn.Open();
                cmd.ExecuteNonQuery();
            }
        }

Open in new window

0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question