3

I am trying to connect to my Azure SQL DB from an azure function written in nodeJS. I have set the connection strings in the application settings and it still does not work. I used ODBC key for connection settings. Did anyone try this? Below is the sample code for my function

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

I am getting an error saying

Exception while executing function: Functions.HttpTriggerJS2. mscorlib: The given key was not present in the dictionary.
Janusz Nowak
  • 2,595
  • 1
  • 17
  • 36
Ross
  • 99
  • 2
  • 12
  • 1
    Try doing the connection as explained here https://learn.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-nodejs – Alberto Morillo Feb 13 '18 at 19:15
  • @AlbertoMorillo That does not work with Azure functions, you have to set the connection settings string in Application settings of the function – Ross Feb 13 '18 at 19:51
  • Did you add: "package.json { "dependencies": { "tedious": "*" } }" as defined here: https://github.com/Azure/azure-functions-host/issues/682 – Alexey Rodionov Feb 14 '18 at 00:32
  • Yes i added the packages and did a npm install from Kudu – Ross Feb 14 '18 at 15:23

1 Answers1

3
  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: '<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);
    }
};

For more information, see Azure Functions JavaScript developer guide.

Ross
  • 99
  • 2
  • 12
Aaron Chen
  • 9,835
  • 1
  • 16
  • 28
  • Thanks for your valuable inputs, yes I did the changes as you suggested and it works. But when I change the SQL query to read a table from my DB it does not work. For example, i have a table called fruits and a query as follows `var sqlQuery = "SELECT apples,oranges FROM fruits; request = new Request(sqlQuery, function(err, rowCount, rows) { .... }` When i do this i get a error saying `RequestError: Invalid object name 'fruits'` – Ross Feb 14 '18 at 14:29
  • @Ross - Did you ever resolve the problem> Sounds like you didn't have the database name in the connection string. – T.J. Crowder Jan 26 '23 at 13:17