1

I have a question, Before I change my code, I got error [error: connection lost: the server closed the connection.], possibly because its idle for sometime. This is my old code.

const dbConn = mysql.createConnection({
    host        : 'localhost',
    user        : 'root',
    password    : '',
    database    : 'test'
});

dbConn.connect(function(err) {
    if(err) throw err;
    console.log("Database Connected!");
})
    
module.exports = dbConn; 

After searching for a while, most of it recommend using createPool intead of createConnection, so I change my code to this

const dbConn = mysql.createPool({
    host        : 'localhost',
    user        : 'root',
    password    : '',
    database    : 'test'
}); 

module.exports = dbConn; 

Then my question is, do I have to release the connection everytime we complete a query? This is how I do query.

dbConn.query("SELECT * FROM spesialisasi s ORDER BY s.nama_spesialisasi ASC ", 
        function(err, res) {
            if(err) {
                console.log("error: ", err);
                result(err, null);
            } else {
                result(null, res);
            }
        }
    )
Ananda Pramono
  • 899
  • 1
  • 6
  • 18

1 Answers1

0

From my knowledge, pool.query() will automatically release the connection when the query completes. Here's the section on connection pooling from the MySQL NPM docs

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
bkw1491
  • 100
  • 1
  • 7