Node.js Sequential interdependent mysql queries

Question:

Problem with Node.js and MySQL There is a need to link several queries, and the subsequent ones will depend on the results of the previous ones. As an example, I took the usual 2 requests for select, I can not link. The first request works, but the second gets an error

Error2 Cannot enqueue Query after invoking quit.

Tell me what's the problem, why doesn't it want to call the second subquery?

var mysql = require('mysql');
var connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'test'
});
connection.query('SELECT * from testtable', function(err, rows, fields) {
  if (!err){
    console.log('Первый запрос: '+rows);
    connection.query('SELECT * from secondtable', function(err2, rows2, fields2) {
      if (!err2){
        console.log('Второй запрос: '+rows2);
      }else{
        console.log('Error2 '+err2);
      }
    });
  }else{
    console.log('Error1 '+err2);
  }
});

Answer:

It was necessary to remove connection.end() after the first connection.query() .

If this is a server that runs "forever", then the easiest option is to keep the connection constantly. A more complex, but correct solution is to use a connection pool that will close itself when idle.

Well, if you rarely need a connection, it is better to open the connection as needed, execute requests, and after completing all – close it.

If we take your case (2 queries), we believe that they need to be executed once and forgotten – I would write something like this:

var mysql = require('mysql');
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'test'
});


connection.query('SELECT * from testtable', function(err, rows, fields) {
  if (err) {
    console.error('Error1', err);
    return connection.end(); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
  }
  console.log('Первый запрос:', rows);
  connection.query('SELECT * from secondtable', function(err, rows2, fields2) {
    connection.end(); //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    if (!err) {
      return console.error('Error2', err);
    }
    console.log('Второй запрос: ' + rows2);
  });

});

But where exactly to insert the closing of the connection is better to think over normally.

P.S. You may be new to asynchrony in node.js. If so – read on this topic.

Scroll to Top