Node-mysql - when to release a connection back to the pool

I am using the node-mysql driver with the connection pool.

Disconnecting a connection back to the pool if there is only one request:

 pool.getConnection(function(err, connection) { if (err) { throw err; } query = "SELECT * FROM user WHERE id = ?"; connection.query(query, [id], function(err, users) { connection.release(); if (err) { throw err; } // ... }); }); 

What if I need to use the connection a second time? I would have to move release() a few lines. But what happens if an error is thrown? Has the connection ever returned to the pool?

Do I need to use some flow control flow to have a β€œfinal” moment in which I could release it?
Any better ideas?

+7
mysql connection-pooling node-mysql
source share
3 answers

One way to process data is promises. Since you are creating a pool, you can build your queries using something like q (or native promises, soon):

 // assuming you have your local getConnection above or imported exports.getConnection = function(queryParams) { var d = q.defer(); local.getConnection(function(err, conn) { if(err) d.reject(err); d.resolve(conn); }); }); 

So, wrap some of your other calls in promises like this, and then just compose your query:

 db.getConnection() .then(function(conn){ makeRequest() .then(...) ... .catch(function(err){ // at the end you release the conn }); 

Does this look like what you are asking for?

+3
source share

When you execute a MySQL query, this time it locks the database until the query completes. Upon successful completion of the request, it releases the database lock.

In the same case: connection.release(); just frees the connection to the database, nothing more.

+1
source share

For this situation you need to use separate connections. To do this, you need a connection pool. Thus, one does not need to wait until the other is complete before he can begin. I use the same connection if one request cannot be started until another request completes.

0
source share

All Articles