Click here to Skip to main content
15,887,244 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my work this question has been raised and there are tendencies towards both sides.
Perhaps connecting and disconnecting overloads the server, against keeping the connection active and consuming licenses.
What do you think about this question?
Thanks...

What I have tried:

I think that the connection should remain open while it is being used and released when it is not required.
Posted
Updated 31-Aug-21 2:54am
v2

Create the connection, open it, use it, close it.

In C#, create the connection object in a using statement, and the system will close and dispose it when the object goes out of scope:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int age = (int) reader["Age"];
                string desc = (string) reader["Description"];
                Console.WriteLine($"{age}\n{desc}");
                }
            }
        }
    }
"Holding" a connection is a bad idea for many reasons: scarce resources, locked files, and a lack of resilience if the DB system fails to a fallback server for example.
 
Share this answer
 
Comments
Maciej Los 31-Aug-21 8:49am    
5ed!
Further to the correct advice in solution 1, note that ADO.NET maintains a pool of the low-level connections so that you don't have to:
Connection Pooling - ADO.NET | Microsoft Docs[^]

If you keep a single connection in use for a long time, you will prevent the connection pool from working efficiently.
 
Share this answer
 
Comments
Maciej Los 31-Aug-21 8:52am    
5ed!
Everyone who says it's OK to hold open a connection to the SQL server for the lifetime of an app needs to learn the phrase "do you want fries with that?"

ALWAYS open your connection as late as possible, do your work as quickly as possible, and close your connection as early as possible.

...and this applies to all resource connections, not just SQL servers.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900