Solved

SqlConnection

Posted on 2011-03-07
2
313 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
The viewer will learn how to implement Singleton Design Pattern in Java.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

733 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