我正在尝试从nodeJS编写的azure函数连接到我的Azure SQL DB。我在应用程序设置中设置了连接字符串,但仍然无效。我使用ODBC密钥进行连接设置。有没有人试过这个?以下是我的功能的示例代码
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
// Create connection to database
const config = process.env["sqldb_connection"];
var connection = new Connection(config);
// Attempt to connect and execute queries if connection goes through
connection.on('connect', function(err)
{
if (err)
{
console.log(err)
}
else
{
queryDatabase()
}
}
);
function queryDatabase()
{ console.log('Reading rows from the Table...');
// Read all rows from table
request = new Request(
"SELECT ORG_ID,ORG_NAME FROM org",
function(err, rowCount, rows)
{
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log("%s\t%s", column.metadata.colName, column.value);
});
});
connection.execSql(request);
}
我收到错误说
Exception while executing function: Functions.HttpTriggerJS2. mscorlib: The given key was not present in the dictionary.
答案 0 :(得分:2)
在npm install tedious
下的 Kudu远程执行控制台中运行D:\home\site\wwwroot
命令。
在Azure Functions中,您的所有代码都应放在module.exports
函数中。
您应该使用context.log()
代替console.log()
。
您实际上不必在功能的应用程序设置中设置连接设置字符串。
您应该在调用context.done()
后通知运行时代码。
以下代码适用于我:
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
module.exports = function (context, req) {
context.log('JavaScript HTTP trigger function processed a request.');
var config = {
userName: '<userName>',
password: '<password>',
server: '<AzureSQLDBName>.database.windows.net',
// If you're on Windows Azure, you will need this:
options:
{
database: 'your DB',
encrypt: true
}
};
var connection = new Connection(config);
connection.on('connect', function(err) {
if (err) {
context.log(err);
context.res = {
status: 500,
body: "Unable to establish a connection."
};
context.done();
} else {
executeStatement();
}
});
function executeStatement() {
request = new Request("select 42, 'hello world'", function(err, rowCount) {
if (err) {
context.log(err);
context.res = {
status: 500,
body: "Failed to connect to execute statement."
};
context.done();
} else {
context.log(rowCount + ' rows');
}
});
request.on('row', function(columns) {
columns.forEach(function(column) {
context.log(column.value);
});
context.done();
});
connection.execSql(request);
}
};
有关详细信息,请参阅Azure Functions JavaScript developer guide。