简体   繁体   English

node-mssql 插入返回未定义的记录集

[英]node-mssql insert returning undefined recordset

Select statements are working fine, but whenever I try an insert or update the recordset and affected values are undefined. Select 语句工作正常,但每当我尝试插入或更新记录集时,受影响的值都是未定义的。 The insert/update works in the DB, I just can't read the returned values.插入/更新在数据库中有效,我只是无法读取返回值。

var sql = require('mssql');
var config = {...};

sql.connect(config).then(function() {
  new sql.Request().query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset, affected) {
    console.log('Recordset: ' + recordset);
    console.log('Affected: ' + affected);
  }).catch(function(err) {
    console.log('Request error: ' + err);
  });
}).catch(function(err) {
  if (err) {
    console.log('SQL Connection Error: ' + err);
  }
});

The output to console is:控制台的输出是:

Recordset: undefined
Affected: undefined

I feel like I must be missing something really simple here.我觉得我一定在这里遗漏了一些非常简单的东西。

As mentioned in the comments, INSERT statement doesn't return a recordset so recordset is undefined.如评论中所述, INSERT语句不返回记录集,因此recordset未定义。 Please see this section of the docs to learn more about how to get number of affected rows.请参阅文档的这一部分以了解有关如何获取受影响行数的更多信息。

The problem with your code is you're expecting affected as a second argument from the promise, but promises does only support one argument.您的代码的问题是您期望affected作为 promise 的第二个参数,但 promises 只支持一个参数。 Because of that you must access number of affected rows this way:因此,您必须以这种方式访问受影响的行数:

var sql = require('mssql');
var config = {...};

sql.connect(config).then(function() {
  var request = new sql.Request();
  request.query("INSERT INTO MyTable (Name, Age) VALUES ('John', 30)").then(function(recordset) {
    console.log('Recordset: ' + recordset);
    console.log('Affected: ' + request.rowsAffected);
  }).catch(function(err) {
    console.log('Request error: ' + err);
  });
}).catch(function(err) {
  if (err) {
    console.log('SQL Connection Error: ' + err);
  }
});

If you want id to be output parameter如果你想 id 作为输出参数

const sql = require("mssql/msnodesqlv8");
const pool = new sql.ConnectionPool(dbConfig);`
const poolConnect = pool.connect();    
let query = `INSERT INTO <table>(fields) VALUES(values);SELECT @id = SCOPE_IDENTITY()`
await poolConnect;
pool.request()
    .output("id", sql.Int)
    .query(query).then((err, result) => {
        console.log(result.output.id)
    }).catch(err => {
        console.log(err)
    })`

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

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