节点mssql插入返回未定义的记录集 [英] node-mssql insert returning undefined recordset

查看:97
本文介绍了节点mssql插入返回未定义的记录集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Select语句工作正常,但是每当我尝试插入或更新记录集时,受影响的值都是不确定的.插入/更新在数据库中有效,我只是无法读取返回的值.

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

控制台输出为:

Recordset: undefined
Affected: undefined

我觉得这里一定缺少一些非常简单的东西.

I feel like I must be missing something really simple here.

推荐答案

如注释中所述,INSERT语句不返回记录集,因此recordset是未定义的.请参阅文档的本节以了解有关如何获取受影响人数的更多信息行.

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.

代码的问题是您期望affected作为promise中的第二个参数,但是promise只支持一个参数.因此,您必须通过以下方式访问受影响的行数:

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

这篇关于节点mssql插入返回未定义的记录集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆