Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What disadvantages are there for leaving an SQL Connection open?

This seems to be a simple question, but I wonder the disadvantages of not calling the "close()" function.

like image 518
stckvrflw Avatar asked Jan 26 '10 12:01

stckvrflw


People also ask

What happens if SQL connection is not closed?

Not closing connections could cause timeouts as the connection pool may run out of available connections that can be used. A side point to this. If you use the using keyword, that will automatically close the connection for you.

Why should I close SQL connection?

This is a basic step that you should consider to be part of mandatory code. If you do not close your database connections, many problems can occur like web pages hanging, slow page loads, and more. Think of it as going through a door to your house. Maybe the door will shut by itself, but maybe it won't.

Should you keep DB connection open?

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.

What happens if you don't close database?

It will stay open in memory, clogging that address until the system times it out and closes it. There was a time that this was a real problem even on small websites. People would open a connection, and it would stay open for weeks. As more users hit that same page, more and more connections would open.


2 Answers

Sooner or later, you'll run into the "The Maximum Connection Limit Has Been Reached" error. I'd call that a major disadvantage.

like image 54
Erich Kitzmueller Avatar answered Oct 21 '22 05:10

Erich Kitzmueller


Apart from exhausting the connection pool (as most answers so far have been), you are in danger of locking data.

If you are reading or writing to a table, some locking semantics will cause certain rows to be locked to other connections. This is especially true if you have any open transaction on the connection.

Reads and writes can then fail and the application will throw exceptions all over the place.

In short, always close the connection.

like image 36
Oded Avatar answered Oct 21 '22 07:10

Oded