Everybody knows that you should close a connection immediately after you finish using it.
Due to a flaw in my domain object model design, I've had to leave the connection open for the full page life cycle. Essentially, I have a Just In Time property which opens a connection on first call, and then on Page.Unload (..) it would check if a db connection was ever open, and then close it if it was. Since it only takes a second, I’ve had the opinion its not too much different than closing it immediately.
Is this ok? Or should it still be closed immediately after every single use?
Thanks in advance.
For fast response time and high throughput, it's actually best to keep database connections open and reuse them for subsequent requests. Most database frameworks offer some kind of connection pool mechanism where a request handler can get a database connection for its work and return it to the pool afterwards.
Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. To ensure that a connection is closed, you could provide a 'finally' block in your code.
After the response is received from the database, the application should be calling close in a finally block. If the application does not explicitly close the connection, that connection will stay open forever in WAS until that server is restarted. This is known as a connection leak.
There is a limit on the number of open connections. So you will eventually run out of connections. It is advisable to close connections when you are done.
No, it is not OK.
If your application will ever need to grow or scale, you'll want to fix this issue. By holding that connection open you're reducing your ability to scale. Keep in mind that open connections take up memory on the server, memory on the client, hold open locks, etc.
What if you page crashes before reaching the Page.Unload event? You will have a opened connection. For me it is better to always close the connection as soon as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With