Fetching multiple mysql queries in one go using QueryQueue
There are times when we need to query mysql database with multiple queries and then process the results together. I am achieving this here using the QueryQueue module built by me. It is available as a npm package.
To start with let us query a hypothetical employee <-> department schema. I am not going into the details of the scheme as it is very straight forward.
Doing it with plain mysql module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var mysql = require("mysql");
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: 'itunes_connect'
});
con.query("SELECT NAME FROM EMPLOYEE WHERE DEPT = ?", ["COMPUTER SCIENCE"], function (err, employees) {
if (err) {
console.log(err);
return;
}
con.query("SELECT NAME FROM DEPARTMENT", [], function (err, departments) {
if (err) {
console.log(err);
return;
}
console.log(employees);
console.log(departments);
});
});
Now doing it the QueryQueue way
1
npm install queryqueue --save
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var QueryQueue = require('queryqueue');
QueryQueue.config({
host: "localhost",
user: "root",
password: "root",
database: 'itunes_connect'
});
var runner = QueryQueue.Runner(function (result) {
console.log(result.employees);
console.log(result.departments);
});
runner.add('employees', "SELECT NAME FROM EMPLOYEE WHERE DEPT = ?", ["COMPUTER SCIENCE"]);
runner.add('departments', "SELECT NAME FROM DEPARTMENT");
runner.start();
A brief explanation
QueryQueue.config - takes database parameters that mysql takes to create connection. This can be done one time in app.js or something similar.
QueryQueue.Runner - takes a callback that is executed once all the queries are completed. The parameter to the callback has the result of each query.
QueryQueue.add - takes a key to which the result is assigned, the query itself and bind parameters if any (optional).
QueryQueue.start - Start the runner and execute all the queries.
NPM package is at -
https://www.npmjs.com/package/queryqueue
Adios…