I'm developing a Node application with ExpressJS and MySQL. I'm working with this module https://github.com/felixge/node-mysql/ and I'm learning its use yet. I get troubles about how to close connections properly.
This is what I do:
app.post('/example', function (req, res) {
//BD
var connection = mysql.createConnection({
host: config.database.host,
port: config.database.port,
user: config.database.user,
password: config.database.password,
database: config.database.database
});
var sql = '';
if (varExample != null) {
sql = 'Random query';
connection.query(sql, function (err, results) {
//Get results
connection.end();
});
}
});
And sometimes I have to call this method several times to insert data in a DB. At that moment I get an error 'Too many connections'.
What is the way to close a connection in these cases?