Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save the result of MySql query in variable using node-mysql [duplicate]

Tags:

node.js

mysql

im trying to save the result of MySql query in variable using node-mysql model and node.js so i have this code:

connection.query("select * from ROOMS", function(err, rows){
if(err) {
    throw err;
} else {
    console.log(rows);
}
});

and the result is :

[ { idRooms: 1, Room_Name: 'dd' },
  { idRooms: 2, Room_Name: 'sad' } ]

so i need to store this results in variable so i try like this:

 var someVar = connection.query("select * from ROOMS", function(err, rows){
if(err) {
    throw err;
} else {
    return rows;
}
});

console.log(someVar);   

but is not working thanks for any help in advance.

like image 356
Fadi Avatar asked Sep 29 '14 12:09

Fadi


4 Answers

Well @Fadi, connection.query is async, which mean when your call your console.log(someVar), someVar has not been set yet.

What you could do:

var someVar = [];

connection.query("select * from ROOMS", function(err, rows){
  if(err) {
    throw err;
  } else {
    setValue(rows);
  }
});

function setValue(value) {
  someVar = value;
  console.log(someVar);
}
like image 58
Rodrigo Medeiros Avatar answered Oct 22 '22 09:10

Rodrigo Medeiros


You can't do that because network i/o is asynchronous and non-blocking in node.js. So any logic that comes afterwards that must execute only after the query has finished, you must place inside the query's callback. If you have many nested asynchronous operations you may look into using a module such as async to help better organize your asynchronous tasks.

like image 41
mscdex Avatar answered Oct 22 '22 09:10

mscdex


As a complement to already given answers.

var **someVar** = connection.query( *sqlQuery*, *callback function( err , row , fields){}* )

console.log(**someVar**);

This construction will return in someVar information of this connection and his SQL query . It will not return values ​​from the query .

Values ​​from the query are located in the callback function ( err , row , fields)

like image 2
Geery.S Avatar answered Oct 22 '22 10:10

Geery.S


Here is your answer if you want to assign a variable to res.render

//before define the values
var tum_render = [];
tum_render.title = "Turan";
tum_render.description = "Turan'ın websitesi";

//left the queries seperatly
var rastgeleQuery = "SELECT baslik,hit FROM icerik ORDER BY RAND() LIMIT 1";
var son5Query = "SELECT baslik,hit FROM icerik LIMIT 5";

var query_arr = [rastgeleQuery, son5Query];
var query_name = ['rastgele', 'son5'];

//and the functions are

//query for db
function runQuery(query_arr,sira){
    connection.query(query_arr[sira], function(err, rows, fields) {
        if (err) throw err;
        var obj = [];
        obj[query_name[sira]] = rows;
        sonuclar.push(obj);
        if (query_arr.length <= sira+1){
            sonuc();
        }else{
            runQuery(query_arr, sira+1);
        }
    });
 }

//the function joins some functions http://stackoverflow.com/questions/2454295/javascript-concatenate-properties-from-multiple-objects-associative-array
function collect() {
      var ret = {};
      var len = arguments.length;
      for (var i=0; i<len; i++) {
        for (p in arguments[i]) {
          if (arguments[i].hasOwnProperty(p)) {
            ret[p] = arguments[i][p];
          }
        }
      }
      return ret;
}

//runQuery callback
function sonuc(){
        for(var x = 0; x<=sonuclar.length-1; x++){
            tum_render = collect(tum_render,sonuclar[x]);
        }
    console.log(tum_render);
    res.render('index', tum_render);
}
like image 1
Gökalp Turan Avatar answered Oct 22 '22 10:10

Gökalp Turan