Question

If we don't close or end mysql connection in node js, is it effects in feature or not.

I am doing like this

var mysql      = require('mysql');
var connection = mysql.createConnection(...);

connection.query('SELECT 1', function(err, rows) {
  // connected! (unless `err` is set)
});

Am not ending mysql connection any where in my code. My question is Is it necessary to close the mysql connection. If we don't close the mysql connection will i face any other problems in future.

Please help me am new to nodejs

EDIT1 I will not face any problems like unable to connect, too many connections to open etc, means any resource related issues? right.

EDIT2

At which instant mysql connection will be close if we don't end it manually or by using end function?

Was it helpful?

Solution

You should close the connection.

The point at which you do it depends on what your program does with that connection.

If the program is long lived and only needs a single connection but uses that connection continuously then you can just leave that one connection open, but you should be be prepared to re-open the connection if required - e.g. if the server gets restarted.

If the program just opens one connection, does some stuff, and then doesn't use the connection for some time you should close the connection while you're not using it.

If the program is short lived, i.e. it makes a connection, does some stuff, and then exits you can get away without closing the connection because it'll get closed automagically when your program exits.

OTHER TIPS

Actually, you will run into problems such as this one from MySQL:

"[host] is blocked because of many connection errors; unblock with ' mysqladmin flush-hosts"

As MySQL will start counting those failed disconnects as "connection errors". And then, your database remains unusable until you execute FLUSH HOSTS on the MySQL server. I know this for a fact, it happened with our NodeJS project.

Write some code to explicitly close the db connection before any output or render statements using connection.end() or connection.destroy()

No you don't need to close it.

If you question is "is there any specific cleanup on mysql side when I tell server that I'm closing connection" then the answer is "no, if you just exit your client process or close socket its the same as calling connection.end()"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top