-4

Every connection needs to be opened and closed. But what time is the best or it depends on the situation?

  1. Open connection when initiate a windows(WPF), form(Windows form), webpage(ASP.NET) and close when the user close window/form/webpage.
  2. Open connection only when user calls the database. For example the user click "Add" button and we run the SQL "INSERT..." then close the connection ASAP. Then if the user click Add/Edit again we have to reconnect to the database, run the SQL and close it ASAP again?

Both solutions have their advantages. By keeping the connection, we will make the program more performance. By keep connecting and disconnecting, the performance will drop.

Red Wei
  • 854
  • 6
  • 22
  • 3
    Close it as soon as you're finished with it, other users might want to access it –  Mar 14 '18 at 09:45
  • Look up "connection pooling", too. – ProgrammingLlama Mar 14 '18 at 09:46
  • 1
    There is no one single answer to this. It depends hugely on context. Note that "opening/closing a web page" doesn't really make sense - the server only sees requests, not client-side page life-cycles, so *at worst* a connection should span a request – Marc Gravell Mar 14 '18 at 09:47
  • @john usually that's handled automatically for you, so ... there isn't really much to do there – Marc Gravell Mar 14 '18 at 09:48
  • I would start with option #2 and see how it performs. If you have issues then see if it is the connections that are causing the problems and change the time they are open/closed to see if it helps. – Simply Ged Mar 14 '18 at 09:50
  • I'd say option 2 is almost always the way to go - because of connection pooling there is almost no perfomance hit doing that. – Evk Mar 14 '18 at 09:51
  • Use the `using`-statement for the connection. So always open/close the connection where you need to access the database. The connection-pooling will do the micro management for you (actually open/close when needed). – Tim Schmelter Mar 14 '18 at 09:55
  • 1
    *"What are your opinions?"* Opinionated questions are off-topic on StackOverflow. – Manfred Radlwimmer Mar 14 '18 at 10:00
  • Hold connections is also good for scaling – paparazzo Mar 14 '18 at 10:38
  • @Marc No, but I wasn't sure if OP knew it existed. – ProgrammingLlama Mar 14 '18 at 10:46

4 Answers4

2

The correct answer is wrap them in a using for the query or queries you want to use them for. Don't hold on to connections for longer then you immediately need. Doing so creates more problems then its worth.

In essence if you need a connection for a bunch of queries just wrap them in a using statement, if they are separated by long running tasks, close them and open them on a piecemeal basis. The worst thing you can so is try to keep them open and check for if they are still alive.

SQL Server Connection Pooling (ADO.NET)

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Furthermore

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. 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. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

In the following example, three new SqlConnection objects are created, but only two connection pools are required to manage them.

Example from MSDN

using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind"))  
{  
    connection.Open();        
// Pool A is created.  
}  

using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=pubs"))  
{  
    connection.Open();        
// Pool B is created because the connection strings differ.  
}  

using (SqlConnection connection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind"))  
{  
    connection.Open();        
// The connection string matches pool A.  
}  

For Controllers WCF services, and CQRS, they are usually short lived, so injecting them in a scoped life cycle is very common. However for things like button clicks in user applications, Service patterns calls, just use them when you need them. Never try to cache or pool.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • And, if you have a try catch inside the using, you can close the connection in the Finally{}, which means that any exception raised by the database activity will still close the connection before bubbling upward. Yes or No? – Allen Feb 07 '22 at 21:56
1

It is better to have a separate project which we call the data layer. The project can have different files for different modules (recommended) or all in one file as you wish. The database layer will expose the various methods like insert, update, get, delete, etc. It is always better to open the connection only for the particular method call and close it as soon as you get the result. You can use the using block like:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();   
    //your code here insert/update/get/delete     
}

The connection will get disposed automatically when the control is out of the using block.

Raviraj Palvankar
  • 879
  • 1
  • 5
  • 9
1

Open the connection and do your operation such as Inserting, Update or Delete and as you get the response close the connection.

to every task open and close connection do not leave connection open in any case

Santosh Singh
  • 561
  • 2
  • 16
1

ASP.NET / Web API / (...)

  • Usually tied to the unit of work pattern, a connection is created for an incoming request then closed when the request has been processed
    • deviations may occur when you have long running background tasks

WPF / Window Forms

  • In this case I would suggest that it's more on a per action basis, even when polling for changes - if that scenario exists
    • Open, Query, Close, repeat
Ricardo Rodrigues
  • 2,198
  • 2
  • 18
  • 22
  • Basically, I implement Unit of Work with Repository Pattern with Dapper. They keep the connection on until GC collect the Unit of Work. – Red Wei Mar 14 '18 at 09:59
  • I think I implement the Unit of Work and Repository the wrong way. – Red Wei Mar 14 '18 at 10:08
  • @RedWei ideally it should be tied to the lifetime of a request so that you don't drain all available connections. From your description seems that you're leaking connections – Ricardo Rodrigues Mar 14 '18 at 10:10
  • @RedWei fun fact: dapper doesn't care whether your connection is open or closed - it'll do the right thing; as long as you don't have temporary tables that span commands, a simple change might be to create but *not open* your connection : any dapper code should continue to work just fine – Marc Gravell Mar 14 '18 at 10:48
  • Thanks @MarcGravell – Red Wei Mar 14 '18 at 10:54