我想知道如何选择一个特定的列来保存到我的函数中的变量。我需要两个值,这就是为什么我有一个查询同时获得两个。我正在使用带有Azure SQL数据库的Node JS,而且我对我的SQL NPM插件使用繁琐。我对此很新,所以任何帮助都会受到赞赏。谢谢!
旁注:返回行数的最底层请求“on done”没有做任何事情。如果有人知道我为什么喜欢知道,这并不重要,但我只是好奇。
function Charge(chipId, LocID) {
request = new Request("SELECT car_id, userOwner FROM Cars WHERE carChipId = '" + chipId + "'", function (err) {
if (err) {
console.log(err);
}
});
var result = "";
request.on('row', function (columns) {
columns.forEach(function (column) {
if (column.value === null) {
console.log('NULL');
} else {
result += column.value + " ";
}
});
console.log(result);
result = "";
});
request.on('done', function (rowCount, more) {
console.log(rowCount + ' rows returned');
});
connection.execSql(request);
}
答案 0 :(得分:1)
尝试以下操作选择保存到变量的特定列:
function charge(chipId) {
var carId = '';
var userOwner = '';
request = new Request(`SELECT car_id, userOwner FROM Cars WHERE carChipId = '${chipId}'`, function(err) {
if (err) {
console.log(err);
}
});
request.on('row', function(columns) {
carId = columns[0].value;
userOwner = columns[1].value;
console.log('carId: ', carId);
console.log('userOwner: ', userOwner);
});
connection.execSql(request);
}
另一个选项是您可以将options.useColumnNames
设置为true
(默认值:false)以将行作为键值集合返回。下面是代码示例。
var config = {
userName: '<userName>',
password: '<password>',
server: '<serverName>.database.windows.net',
options: {
encrypt: true,
database: '<database>',
useColumnNames: true
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
charge('<chipId>');
});
function charge(chipId) {
var carId = '';
var userOwner = '';
request = new Request(`SELECT car_id, userOwner FROM Cars WHERE carChipId = '${chipId}'`, function(err) {
if (err) {
console.log(err);
}
});
request.on('row', function(columns) {
carId = columns.car_id.value;
userOwner = columns.userOwner.value;
console.log('carId: ', carId, ' userOwner: ', userOwner);
});
connection.execSql(request);
}
如果您想Event: done
被触发,请使用connection.execSqlBatch(request)
代替connection.execSql(request)
。有关详细信息,请参阅http://tediousjs.github.io/tedious/api-connection.html#function_execSqlBatch。