节点mssql插入返回未定义的记录集 [英] node-mssql insert returning undefined recordset
问题描述
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屋!