简体   繁体   中英

Release Connection When Query Is Complete

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);
            }
        }
    )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM