2

我正在尝试从数据库中获取数据,但收到以下错误{消息:'请求只能在 LoggedIn 状态下进行,而不是 SentClientRequest 状态',代码:'EINVALIDSTATE'}。如果我只调用一个查询函数,那么它可以工作,但不能用于多个

下面是我的代码

var connection = new Connection(config);
connection.on('connect', function(err) {
// If no error, then good to proceed.
if(!err)
{
    console.log("Connected");
    executeStatement();
    executeStatement2();
}
else
{
    console.log(err);
}
});

var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;

function executeStatement() {
request = new Request("Select p.product_name, s.product_id, s.price,   s.create_date, s.update_date from products p left join sale s on (p.id = s.product_id) order by CONVERT(datetime, s.update_date ) desc ;", function(err) {
    if (err) {
        console.log(err);}
});

request.on('row', function(columns) {
        var rowObject ={};
        columns.forEach(function(column) {
            rowObject[column.metadata.colName] = column.value;
        });
        var jsonArray = [];
        jsonArray.push(rowObject);

});

connection.execSql(request);
}


function executeStatement2() {
request = new Request("Select * from products ;", function(err) {
    if (err) {
        console.log(err);
    }
});

request.on('row', function(columns) {
    var rowObject ={};
    columns.forEach(function(column) {
        rowObject[column.metadata.colName] = column.value;
    });
    var jsonArray2 = [];
    jsonArray2.push(rowObject);

});
 connection.execSql(request);
}
4

2 回答 2

4

我有同样的问题。您不能运行两个不同的查询请求。解决方案是使用一个查询请求和

request.on('requestCompleted', function () { // Next SQL statement. });

本期提到: https ://github.com/tediousjs/tedious/issues/458

于 2017-11-08T08:24:54.757 回答
0

我在https://github.com/tediousjs/tedious/issues/458找到了一个不错的解决方案。我有同样的问题,这个解决方案解决了我的问题

const {Connection, Request} = require("tedious");
const executeSQL = (sql, callback) => {
  let connection = new Connection({
    "authentication": {
      "options": {
        "userName": "USERNAME",
        "password": "PASSWORD"
      },
      "type": "default"
    },
    "server": "SERVER",
    "options": {
      "validateBulkLoadParameters": false,
      "rowCollectionOnRequestCompletion": true,
      "database": "DATABASE",
      "encrypt": true
    }
  });
  connection.connect((err) => {
    if (err)
      return callback(err, null);
    const request = new Request(sql, (err, rowCount, rows) => {
      connection.close();
      if (err)
        return callback(err, null);
      callback(null, {rowCount, rows});
    });
    connection.execSql(request);
  });
};
executeSQL("SELECT * FROM users", (err, data) => {
  if (err)
    console.error(err);
  console.log(data.rowCount);
});
//or
executeSQL("SELECT * FROM users", (err, {rowCount, rows}) => {
  if (err)
    console.error(err);
  console.log(rowCount);
});
于 2022-02-15T09:11:21.633 回答