Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Database & SysAdmin
  3. Database
  4. Is it a bad idea to keep a Database connection open

Is it a bad idea to keep a Database connection open

Scheduled Pinned Locked Moved Database
databasesysadminsql-serverwinformsdebugging
10 Posts 5 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R Offline
    R Offline
    Richard Berry100
    wrote on last edited by
    #1

    I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

    L P G J R 5 Replies Last reply
    0
    • R Richard Berry100

      I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #2

      Richard.Berry100 wrote:

      Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed?

      Yes. Opening/closing a connection takes very little time. There's a connection-pool that manages the connections. Another advantage of closing your connection is that you'll be able to handle more client-connections. If your server can handle 25 clients simultaneous, how much would it be able to handle if they only connect when required?

      Richard.Berry100 wrote:

      Will the connection stay open, or will SQL server drop it if it is unused for some time?

      That'd be easy to test, wouldn't it? Write a console-app and tell us if it indeed stays open as it should; there's only a timeout on creating a connection and on executing statements, not on the lifetime of the connection. That doesn't mean that the server will guarantee an open connection. A single Windows-update could force a reboot and close the connection. Or the cleaning-lady, when she unplugs the server and plugs in her vacuum-cleaner :) --edit Here's the link I was looking for; SQL Server Connection Pooling (ADO.NET)[^]

      To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling. [...] It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool.

      Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

      R 1 Reply Last reply
      0
      • R Richard Berry100

        I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

        P Offline
        P Offline
        PIEBALDconsult
        wrote on last edited by
        #3

        Yes. I instantiate and dispose the connection only once, but I open and close it for each operation.

        1 Reply Last reply
        0
        • R Richard Berry100

          I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

          G Offline
          G Offline
          GuyThiebaut
          wrote on last edited by
          #4

          Define your connection at the start, then for each operation open then close the connection once the operation is complete.

          “That which can be asserted without evidence, can be dismissed without evidence.”

          ― Christopher Hitchens

          1 Reply Last reply
          0
          • R Richard Berry100

            I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

            J Offline
            J Offline
            jschell
            wrote on last edited by
            #5

            Richard.Berry100 wrote:

            Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed?

            Normal MS stuff uses a connection pool. The first time you create the connection it is opened. After that it gets it from the pool. It is already open and it stays open. It never closes while the application runs. That is the default behavior of the connection pool. Your suggestion is doing nothing more than priming the pump to make it appear later that your application is more responsive. So 1. There is nothing wrong with doing that. 2. It is unlikely to have any impact on the database server nor the architecture 3. It is a perfectly reasonable thing to do.

            Richard.Berry100 wrote:

            or will SQL server drop it if it is unused for some time?

            No SQL Server will not close idle connections. That itself is actually a problem because it means that if a client connection crashes (client fails or network fails) that the connection just remains there forever. One either must set up a process to clean them or at least look for them every once in a while.

            P 1 Reply Last reply
            0
            • J jschell

              Richard.Berry100 wrote:

              Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed?

              Normal MS stuff uses a connection pool. The first time you create the connection it is opened. After that it gets it from the pool. It is already open and it stays open. It never closes while the application runs. That is the default behavior of the connection pool. Your suggestion is doing nothing more than priming the pump to make it appear later that your application is more responsive. So 1. There is nothing wrong with doing that. 2. It is unlikely to have any impact on the database server nor the architecture 3. It is a perfectly reasonable thing to do.

              Richard.Berry100 wrote:

              or will SQL server drop it if it is unused for some time?

              No SQL Server will not close idle connections. That itself is actually a problem because it means that if a client connection crashes (client fails or network fails) that the connection just remains there forever. One either must set up a process to clean them or at least look for them every once in a while.

              P Offline
              P Offline
              PIEBALDconsult
              wrote on last edited by
              #6

              It is still preferable to use Open to get the connection from the pool and Close to return it.

              J 1 Reply Last reply
              0
              • R Richard Berry100

                I am using a windows forms application to write data to a SQL 2008 database over a wireless network. (Scanning serial numbers) While stepping through the code in debug mode, the Connection.Open seems to take relatively long. Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed? Will the connection stay open, or will SQL server drop it if it is unused for some time?

                R Offline
                R Offline
                Richard Berry100
                wrote on last edited by
                #7

                Hi Guys - thanks to all for the responses. I think the link Eddy posted puts a lot into perspective, in that closing the connection does not really kill it, it leaves it in the pool, and unless there is something in the connection that changes, like accessing a different database, or using a different User ID the same connection from that pool is used again. I tried inserting 10000 records (on server on local machine) in three different ways. The difference was only about 100ms

                private void cmdInsert_Click(object sender, EventArgs e)
                {
                Stopwatch sw = new Stopwatch();
                string cnStr = "Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + DBUser + "; Password=" + DBPass + ";";
                string strSql = "Insert INTO dbo.SpeedTest (Mydata) VALUES ('Hello')";
                sw.Start();
                using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnStr))
                {

                            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strSql, cn);
                            
                	for (int i = 0; i < 10000; i++)
                            {
                                cn.Open();
                                cmd.ExecuteNonQuery();
                                cn.Close();
                            }
                        }
                
                        sw.Stop();
                        this.txtResults.Text = sw.ElapsedMilliseconds.ToString();
                                  
                    }
                

                //7958 miliseconds

                private void cmdInsert_Click(object sender, EventArgs e)
                {
                Stopwatch sw = new Stopwatch();
                string cnStr = "Data Source=" + Server + ";Initial Catalog=" + Database + ";User Id=" + DBUser + "; Password=" + DBPass + ";";
                string strSql = "Insert INTO dbo.SpeedTest (Mydata) VALUES ('Hello')";
                sw.Start();
                using (System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(cnStr))
                {

                            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strSql, cn);
                            cn.Open();
                	for (int i = 0; i < 10000; i++)
                            {
                                
                                cmd.ExecuteNonQuery();
                                
                            }
                            cn.Close();
                        }
                
                        sw.Stop();
                        this.txtResults.Text = sw.ElapsedMilliseconds.ToString();
                                  
                    }
                

                //6894 miliseconds

                private void cmdInsert_Click(object sender, EventArgs e)
                {

                1 Reply Last reply
                0
                • L Lost User

                  Richard.Berry100 wrote:

                  Is it bad practice to open a connection when the application starts, to avoid delays caused by opening the connection each time a query is executed?

                  Yes. Opening/closing a connection takes very little time. There's a connection-pool that manages the connections. Another advantage of closing your connection is that you'll be able to handle more client-connections. If your server can handle 25 clients simultaneous, how much would it be able to handle if they only connect when required?

                  Richard.Berry100 wrote:

                  Will the connection stay open, or will SQL server drop it if it is unused for some time?

                  That'd be easy to test, wouldn't it? Write a console-app and tell us if it indeed stays open as it should; there's only a timeout on creating a connection and on executing statements, not on the lifetime of the connection. That doesn't mean that the server will guarantee an open connection. A single Windows-update could force a reboot and close the connection. Or the cleaning-lady, when she unplugs the server and plugs in her vacuum-cleaner :) --edit Here's the link I was looking for; SQL Server Connection Pooling (ADO.NET)[^]

                  To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling. [...] It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool.

                  Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

                  R Offline
                  R Offline
                  Richard Berry100
                  wrote on last edited by
                  #8

                  Thanks Eddy, good link!

                  1 Reply Last reply
                  0
                  • P PIEBALDconsult

                    It is still preferable to use Open to get the connection from the pool and Close to return it.

                    J Offline
                    J Offline
                    jschell
                    wrote on last edited by
                    #9

                    PIEBALDconsult wrote:

                    It is still preferable to use Open to get the connection from the pool and Close to return it.

                    I would say it is the only way.

                    R 1 Reply Last reply
                    0
                    • J jschell

                      PIEBALDconsult wrote:

                      It is still preferable to use Open to get the connection from the pool and Close to return it.

                      I would say it is the only way.

                      R Offline
                      R Offline
                      Richard Berry100
                      wrote on last edited by
                      #10

                      Yip, agreed, see the reply I posted to my own question with speed tests on various approaches, and reference to Eddy's link - Thanks!

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups