Welcome to Dream.In.Code
Getting C# Help is Easy!

Join 136,104 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 1,687 people online right now. Registration is fast and FREE... Join Now!




When to close SqlConnection and SqlReader

 
Reply to this topicStart new topic

When to close SqlConnection and SqlReader, Were you born in a barn!?

tommahhh
20 Nov, 2007 - 04:02 PM
Post #1

New D.I.C Head
*

Joined: 19 Nov, 2007
Posts: 4


My Contributions
Hi Everyone,

I was just wondering when it was appropriate to close a sql connection and a sql reader. Do I need to close them everytime on every error? Here's my code:

CODE


protected void loginButton_Click(object sender, EventArgs e)
        {
            int loginID = 0;
            DataAccess DA = new DataAccess();

            try
            {
                // create the parameterized command and execute it
                SqlCommand cmd = new SqlCommand("select LoginID, Login, Password from Login where Login = @Login and Password = @Password");
                cmd.Parameters.AddWithValue("@Login", userIDTextBox.Text);
                cmd.Parameters.AddWithValue("@Password", passwordTextBox.Text);

                SqlDataReader reader = DA.GetDataReader(cmd);

                if (reader != null)
                {
                    // if the database returned no rows then we do not have a valid input
                    if (reader.HasRows == false)
                    {
                        loginFailedLabel.Text = "Login Failed.";
                        reader.Close();
                        DA.CloseConnection();
                        return;
                    }
                    else
                    {
                        // grab the loginID
                        reader.Read();
                        loginID = Int32.Parse(reader["LoginID"].ToString());

                        reader.Close();
                    }
                }
                else
                {
                    loginFailedLabel.Text = DA.WriteError();
                    return;
                }

                // user is authenticated, set the PartnerID session variable
                cmd = new SqlCommand("select PartnerID from Partner where LoginID = @LoginID");
                cmd.Parameters.Add("LoginID", loginID);
                reader = DA.GetDataReader(cmd);

                if (reader != null)
                {
                    reader.Read();
                    Session["PartnerID"] = Int32.Parse(reader["PartnerID"].ToString());

                    reader.Close();
                    DA.CloseConnection();

                }
                else
                {
                    loginFailedLabel.Text = DA.WriteError();
                    return;
                }

            }
            catch (SqlException exception)
            {
                loginFailedLabel.Text = DA.WriteError("REACH.Master.cs: Line: " + exception.LineNumber + ": " + exception.ToString(), true);
                return;
            }



Btw DA.WriteError opens the connection on initization and closes it on DA.CloseConnection and on DA.WriteError at the moment.

So should I be closing both the reader and connection on each 'else' and on the 'catch'? Or do I really care?

Thanks!

Tom
User is offlineProfile CardPM
+Quote Post

baavgai
RE: When To Close SqlConnection And SqlReader
20 Nov, 2007 - 05:13 PM
Post #2

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,019



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
Normally, you try to spend as little time with a connection open as possible. You open late and close early. If this means you open and close a few times, well, that's better than leaving something open.

I posted a snippet on this pattern here.

The next thing you can do is see how to shorten the database trips. The code you offer here need only visit the database once.

Given what you've written, I might write it like so:
CODE


DataAccess DA = new DataAccess();
SqlDataReader reader = null;
SqlCommand cmd = new SqlCommand("select"
    + " a.LoginID, a.Login, a.Password, b.PartnerID"
    + " from Login a"
    + " left outer join Partner b on a.LoginID=b.LoginID"
    + " where a.Login = @Login"
    + " and a.Password = @Password"
);
cmd.Parameters.AddWithValue("@Login", userIDTextBox.Text);
cmd.Parameters.AddWithValue("@Password", passwordTextBox.Text);

try {
    //I'm assuming DA.GetDataReader opens the connection,
    // otherwise you wont get very far.
    reader = DA.GetDataReader(cmd);
    if (reader.read()) {
        Session["LoginID"] = Int32.Parse(reader["LoginID"].ToString());
        Session["PartnerID"] = Int32.Parse(reader["PartnerID"].ToString());
    } else {
        loginFailedLabel.Text = "Login Failed.";
        //loginFailedLabel.Text = DA.WriteError();
    }
} catch (SqlException exception) {
    loginFailedLabel.Text = DA.WriteError("REACH.Master.cs: Line: " + exception.LineNumber + ": " + exception.ToString(), true);
    return;
} finally {
    if (reader!=null) { reader.Close(); }
    DA.CloseConnection();
}


Hope this helps.

User is offlineProfile CardPM
+Quote Post

tommahhh
RE: When To Close SqlConnection And SqlReader
20 Nov, 2007 - 05:31 PM
Post #3

New D.I.C Head
*

Joined: 19 Nov, 2007
Posts: 4


My Contributions
Thank you baavgai, that is much cleaner. One last question: does the finally block get executed even with the return statement in the catch block?
User is offlineProfile CardPM
+Quote Post

baavgai
RE: When To Close SqlConnection And SqlReader
20 Nov, 2007 - 07:29 PM
Post #4

Dreaming Coder
Group Icon

Joined: 16 Oct, 2007
Posts: 2,019



Thanked: 105 times
Dream Kudos: 475
Expert In: C, C++, Java, C#, ASP.NET, PHP, Perl, Python, Oracle, SQL Server, MySql, HTML, JavaScript, Lua

My Contributions
QUOTE(tommahhh @ 20 Nov, 2007 - 08:31 PM) *

Thank you baavgai, that is much cleaner. One last question: does the finally block get executed even with the return statement in the catch block?


Yep. Returns and exceptions will leave the try block, but not before finally executes.

Think of it as your last chance to clean stuff up. You try to keep the code in the block short and sweet, so there's little chance of bad things happening. Yes, you can nest try blocks into absurdity.

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic
Time is now: 12/1/08 09:05PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month