troubleshooting Question

How to close database connection?

Avatar of novknow
novknow asked on
C#
6 Comments2 Solutions254 ViewsLast Modified:
I am trying to close database connection in a finally block like this:

            SqlCommand cmd = new SqlCommand(someString, someConnection);
            SqlDataReader reader = cmd.ExecuteReader();
            try
            {
                if (reader.Read())
                {
                    ...
                }
            }
            catch (SystemException ex)
            {
            }
            finally
            {
                reader.Close();
            }

But the code goes hay wire if there is error in the SQL statement in someString.
So I tried this:

            SqlCommand cmd = new SqlCommand(someString, someConnection);
            try
            {
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    ...
                }
            }
            catch (SystemException ex)
            {
            }
            finally
            {
                reader.Close();
            }

But C# compiler says "The name 'reader' does not exist in the current context".
So I tried this:

    SqlCommand cmd = new SqlCommand(someString, someConnection);
    SqlDataReader reader;
            try
            {
                reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    ...
                }
            }
            catch (SystemException ex)
            {
            }
            finally
            {
                reader.Close();
            }

But C# compiler says "Use of unassigned local variable 'reader'".
So I tried this:

Question:
What is the correct and sure way to code to make sure the connection is closed
after reading the data from the database?

regards
ASKER CERTIFIED SOLUTION
redpipe

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 2 Answers and 6 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros