如何使用node-mysql在变量中保存MySql查询的结果

时间:2021-10-26 15:41:37

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

我试图使用node-mysql模型和node.js在变量中保存MySql查询的结果,所以我有这样的代码:

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.

但是没有工作,谢谢你提前帮助。

4 个解决方案

#1


9  

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

那么@Fadi,connection.query是异步的,这意味着当你调用console.log(someVar)时,someVar尚未设置。

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);
}

#2


2  

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.

你不能这样做,因为网络i / o在node.js中是异步和非阻塞的。因此,之后出现的任何必须在查询完成后才能执行的逻辑,必须放在查询的回调中。如果您有许多嵌套异步操作,您可能会考虑使用async等模块来帮助更好地组织异步任务。

#3


2  

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 .

此构造将返回此连接的一些零信息和他的SQL查询。它不会返回查询中的值。

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

查询中的值位于回调函数中(错误,行,字段)

#4


1  

Here is your answer if you want to assign a variable Res.render: (but comments turkish)

如果你想分配一个变量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://*.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);
}

#1


9  

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

那么@Fadi,connection.query是异步的,这意味着当你调用console.log(someVar)时,someVar尚未设置。

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);
}

#2


2  

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.

你不能这样做,因为网络i / o在node.js中是异步和非阻塞的。因此,之后出现的任何必须在查询完成后才能执行的逻辑,必须放在查询的回调中。如果您有许多嵌套异步操作,您可能会考虑使用async等模块来帮助更好地组织异步任务。

#3


2  

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 .

此构造将返回此连接的一些零信息和他的SQL查询。它不会返回查询中的值。

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

查询中的值位于回调函数中(错误,行,字段)

#4


1  

Here is your answer if you want to assign a variable Res.render: (but comments turkish)

如果你想分配一个变量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://*.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);
}