Connect to Azure SQL DB from a Azure Functions in JS


  1. Run the npm install tedious command in the Kudu remote execution console under D:\home\site\wwwroot.


  2. In Azure Functions, all of your code should be put inside the module.exports function.


  3. You should use context.log() instead of console.log().


  4. You really don't have to set the connection settings string in Application settings of the function.


  5. You should inform the runtime when your code has finished by calling context.done().




The following code works for me:



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: '',
password: '',
server: '.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);
}
};


For more information, see Azure Functions JavaScript developer guide.


More: