Search code examples
mysqlnode.jsnode-mysql

Store mysql query rows in variable for later use


I'm doing a monitoring system project in which I have Arduino sensors data being sent to a node.js server (thru GET requests) and then stored in a MySQL DB.

Whenvever I successfully send data to the server, it connects to the MySQL DB and queries the last 5 received records to do some processing.

Therefore, I need to store the rows of those 5 records in a variable for later use. Meaning that I have to get rows from a connection.query in a variable.

I read that the fact that I'm not able to do this is because node.js being async. So my questions are:

  1. Is it possible to do the described tasks the way I'm trying?
  2. If not, is there any other way to do so?

I'm not putting the whole code here but I'm running a separated test that also doesn't run properly. Here it is:

var mysql = require('mysql');

var con = mysql.createConnection({
      host    : "127.0.0.1",
      user    : "root",
      password: "xxxx",
      database: "mydb",
      port    : 3306
});
var queryString = "SELECT id, temp1, temp2, temp3, temp4, level_ice_bank, flow FROM tempdata ORDER BY id DESC LIMIT 5";

con.connect(function(err) {
  if (err) throw err;
});

var result_arr = [];
function setValue (value) {
  result_arr = value;
}

con.query(queryString, function (err, rows, fields) {
  if (err) throw err;
  else {
    //console.log(rows);
    setValue(rows);
  }
});

console.log(result_arr);

It logs:

[]

But if I uncomment console.log(rows); it logs what I need to store in the variable result_arr.

Thanks in advance to all.


Solution

  • You're seeing this behaviour because con.query(...) is an asynchronous function. That means that:

    console.log(result_arr);
    

    Runs before:

    con.query(queryString, function (err, rows, fields) {
      if (err) throw err;
      else {
        //console.log(rows);
        setValue(rows);
      }
    });
    

    (Specifically, the setValue(rows) call)

    To fix this in your example, you can just do:

    con.query(queryString, function (err, rows, fields) {
      if (err) throw err;
      else {
        setValue(rows);
        console.log(result_arr);
      }
    });
    

    If you want to do more than just log the data, then you can call a function which depends on result_arr from the con.query callback, like this:

    con.query(queryString, function (err, rows, fields) {
      if (err) throw err;
      else {
        setValue(rows);
        doCleverStuffWithData();
      }
    });
    
    function doCleverStuffWithData() {
        // Do something with result_arr
    }