简体   繁体   English

从Node.js中的SQL查询返回变量

[英]Return a variable from sql query in Node.js

I have MySQL query in Node.js where I'm trying to return "variable" and assign in to getVarible OUTSIDE my query. 我在Node.js中有MySQL查询,在其中我试图返回“变量”并分配给getVarible我的查询之外。 Is it possible to do in this case? 在这种情况下可以这样做吗? If so, how? 如果是这样,怎么办?

Here is my code : 这是我的代码:

var sqlQuery = connection.query(result, function(err, rows, fields) {
        var count = rows.length;
        if(count === 1){
            var variable = rows[0].item;
            return variable;
        }            
    }
});

var getVariable = variable;

If you declare getVariable before your query call, you should be able to access it once your query return, within your cacllback fuction. 如果在查询调用之前声明getVariable,则在返回查询后,应该可以在cacllback功能内访问它。 You can try something like this: 您可以尝试如下操作:

var getVariable = {};

var sqlQuery = connection.query(result, function(err, rows, fields) {
        var count = rows.length;
        if(count === 1){
            getVariable = rows[0].item;
        }            
    }
});

However keep in mind that query execution is asynchronous, so your variable will be empty until your callback is executed. 但是请记住,查询执行是异步的,因此在执行回调之前,变量将为空。

So I would suggest you all logic where you use that variable to be executed within callback or use a promise of async framework. 因此,我建议您使用所有在回调中执行该变量或使用apromise异步框架的逻辑。

Your connection.query does not return what you think it returns ie return variable; 您的connection.query不会返回您认为返回的结果,即return variable; statement has no effect. 声明无效。

Checkout the API with the usage of query object. 使用查询对象的用法检出API。

var query = connection.query('SELECT * FROM posts');
query
  .on('error', function(err) {
    // Handle error, an 'end' event will be emitted after this as well
  })
  .on('fields', function(fields) {
    // the field packets for the rows to follow
  })
  .on('result', function(row) {
    // Pausing the connnection is useful if your processing involves I/O
    connection.pause();

    processRow(row, function() {
      connection.resume();
    });
  })
  .on('end', function() {
    // all rows have been received
  });

Alternatively you can have a short hand to handle the success, error by using the second parameter to connection.query . 或者,您可以使用第二个参数connection.query来帮助您成功处理错误。 This is a function with signature function (error, results, fields) which does the same thing as above API. 这是一个具有签名function (error, results, fields)的函数,其功能与上述API相同。

connection.query(sqlQueryStr, function (error, results, fields) {})

The call to connection.query is asynchronous and the function passed as the second argument is executed only after the results are available ie the query has executed. connection.query的调用是异步的,仅在结果可用(即查询已执行)之后才执行作为第二个参数传递的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM