Search code examples
mysqlnode.jsnode-mysqlnode-modules

Is there is any problems if we don't close the mysql connection in mysql node js module


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?


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.