Nested query in node js using mysql

I am trying to execute the following code in node js using mysql, but I get the error message "Cannot make a Query query after calling quit.

var mysql = require('mysql'); var connection = mysql.createConnection({ host : 'localhost', user : 'USER', password : 'PASS', database : 'DB', }); connection.connect(); var queryString = 'SELECT * FROM tbl_product'; connection.query(queryString, function(err, rows, fields) { if (err) throw err; for (var i in rows) { console.log('Product Name: ', rows[i].product_name); var emp_query = 'SELECT * FROM tbl_employer'; connection.query(queryString, function(emp_err, emp_rows, emp_fields) { if (emp_err) throw emp_err; for (var e in emp_rows) { console.log('Employer Name: ', emp_rows[e].company_name); } }); } }); connection.end(); 
+6
source share
3 answers

Delete the final connection function

==> connection.end();

+3
source

I see two problems in your code:

  • You call connection.end() synchronously, but your requests are executed in an asynchronous thread. You should call connection.end() only after the second request completes.
  • You use the regular for loop to start asynchronous calls (you can use the outter loop).

To accomplish what you are trying to do, you must consider these asynchronous scripts. You can use promises or a module like async , which provides you with many ways to deal with assyncronous streams, such as async.each() :

 connection.query(queryString, function(err, rows, fields) { if (err) throw err; async.each(rows, function (row, callback) { console.log('Product Name: ', row.product_name); var emp_query = 'SELECT * FROM tbl_employer'; connection.query(queryString, function(emp_err, emp_rows, emp_fields) { if (emp_err) callback(emp_err); for (var e in emp_rows) { console.log('Employer Name: ', emp_rows[e].company_name); } callback(); }); }); }, function (err) { connection.end(); } }); 

Now this ensures that connection.end() will only be called after all of your requests have completed.

+5
source

The connection.end() problem is triggered before your request is not finished yet. Try putting connection.end() at the end of the outer loop.

 connection.query(queryString, function(err, rows, fields) { if (err) throw err; for (var i in rows) { console.log('Product Name: ', rows[i].product_name); var emp_query = 'SELECT * FROM tbl_employer'; connection.query(queryString, function(emp_err, emp_rows, emp_fields) { if (emp_err) throw emp_err; for (var e in emp_rows) { console.log('Employer Name: ', emp_rows[e].company_name); } }); } connection.end(); }); 

Hope this will be helpful for you.

+1
source

Source: https://habr.com/ru/post/984431/


All Articles