Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node-mysql where does connection.end() go

Tags:

I am really confused with using connection.end() in node-mysql.

I don't fully understand where it goes, at the moment i place it after a query but then if i create a new query i get an error Cannot enqueue Query after invoking quit.

Now my app has a bunch of checks going here is one of them:

   socket.on('connect', function(data,callBack){
       var session = sanitize(data['session']).escape();                    

       var query = connection.query('SELECT uid FROM sessions WHERE id = ?', [session],
           function(err,results){
           if(err){ 
                  console.log('Oh No! '+err);                   
              }else{
                  io.sockets.socket(socket.id).emit('connectConfirm',{data : true});
              }
              connection.end();
           });
   });

Now after that if i have any other query i get the error occuring.

I made a more informed explaination in my jsFiddle: http://jsfiddle.net/K2FBk/ to better explain the problem I'm getting. The documentation for node-mysql does not totally explain the correct place to put connection.end()

Where should it go to avoid this error?

like image 938
Sir Avatar asked Dec 19 '13 22:12

Sir


2 Answers

Per the documentation:

Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.

connection.end() is then supposed to be called only when you stop sending queries to MySQL, i.e. when your application is stopping. You shouldn't create/end connections all the time: just use the same connection for all your queries (or use a connection pool to be more efficient).

like image 147
Paul Mougel Avatar answered Nov 11 '22 01:11

Paul Mougel


socket.on('connect', function(data,callBack){
       var session = sanitize(data['session']).escape();                    

       var query = connection.query('SELECT uid FROM sessions WHERE id = ?', [session],
           function(err,results){
           if(err){ 
                  console.log('Oh No! '+err);                   
              }else{
                  io.sockets.socket(socket.id).emit('connectConfirm',{data : true});
              }

           });

       connection.end(); // close connection outside the callback
   });

Its giving error because you are closing connection during en-queue

like image 41
VIKAS KOHLI Avatar answered Nov 11 '22 03:11

VIKAS KOHLI