Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

SqlConnection

Posted on 2011-03-07
2
Medium Priority
?
323 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 2000 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 2000 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: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say 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

Before we dive into the marketing strategies involved with creating an effective homepage, it’s crucial that EE members know what a homepage is. In essence, a homepage is the introductory, or default page, of a website that typically highlights the …
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
Suggested Courses

783 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