Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it acceptable to keep a db connection open for the life of the page?

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.

like image 288
John MacIntyre Avatar asked Nov 19 '08 15:11

John MacIntyre


People also ask

Is it safe to keep database connection open for long time?

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.

Should I close database connection?

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.

What happens if database connection is not closed?

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.

Should I close DB connection after query?

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.


2 Answers

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.

like image 128
Scott Ivey Avatar answered Sep 22 '22 09:09

Scott Ivey


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.

like image 34
Bruno Shine Avatar answered Sep 21 '22 09:09

Bruno Shine