node-mssql insert returning undefined recordset

青春壹個敷衍的年華 提交于 2020-01-05 09:07:00

问题


Select statements are working fine, but whenever I try an insert or update the recordset and affected values are undefined. 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.


回答1:


As mentioned in the comments, INSERT statement doesn't return a recordset so recordset is undefined. 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. 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);
  }
});


来源:https://stackoverflow.com/questions/34615684/node-mssql-insert-returning-undefined-recordset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!