Alex Alex - 3 months ago 16
Node.js Question

how much connection.release() must have in node js code?

I am using node js for web service I use

pool.getConnection()
in my code , after use
pool.getConnection()
for close this connection i am using
connection.release();
but in any query i am not use any function for close connection .please tell me this code is valid or not?.

pool.getConnection(function(err,connection){
connection.release();
if(!err){
email=req.user.email
connection.query('select * from users where email=?',[email],
function(err,user_detail){
if(!err)
{
connection.query('insert into message(??,time,type,user_id) values(?,?,?,?)',[messagecolumns,dbValues,time,type,user_id],
function(err,message_inserted){
if(!err)
{
console.log('Message send',message_inserted.insertId);
connection.query('select u.firstname,u.lastname,u.img_path,m.* from users u, message m where u.id=m.user_id and m.id=?',[message_inserted.insertId],
function(err,message_detail){
if(!err)
{
connection.query('select count(id) as message_count from message where appointment_request_id=?',[appointment_request_id],
function(err,total_message){
if(!err)
{
connection.query('update appointment_request set message_count=? where appointment_request_id=?',[total_message[0].message_count,appointment_request_id],
function(err,update_message_count){
if(!err)
{
}
});
}
else {
console.log('connection Error',err);
}


I feel this is not valid method for connection because from some web site I realize that after SQL query I must close connection but in this code I never use any close connection and my code are some time give me 500 server error and some time it work successfully so I have to fix this error and I want to permanently solution if anyone can help me please give me solution for this. if you have any confutation for understanding you may ask me .

Thanks

Answer

A pool has a limited number of connections (Default is 10).

When you getConnection then one of those connections is removed from pool and is passed to you so that you can use it. You will call connection.release() after you are finished working with the connection. As soon as you called connection.release() the connection is passed back to the pool and is free to be used by other parts of your code. As of that it is not valid to work with this connection after you have called release on it, because it might be closed or used by another part of your code that requested a connection with getConnection (in most of the cases it might still work, but it could unexpectedly fail).

In your code you call connection.release(); at the beginning of you callback so the usage of connection after that release is not valid.

You you must not call connection.release() multiple times on the same connection.