node.jsazure-sql

Nothing happens when connecting to Azure SQL Database from Node.js


Following the Microsoft provided instructions, I used the below code. https://learn.microsoft.com/en-us/azure/azure-sql/database/connect-query-nodejs?tabs=windows

const { Connection, Request } = require("tedious");

// Create connection to database
const config = {
  authentication: {
    options: {
      userName: "username", // update me
      password: "password" // update me
    },
    type: "default"
  },
  server: "your_server.database.windows.net", // update me
  options: {
    database: "your_database", //update me
    encrypt: true
  }
};

const connection = new Connection(config);

// Attempt to connect and execute queries if connection goes through
connection.on("connect", err => {
  if (err) {
    console.error(err.message);
  } else {
    queryDatabase();
  }
});

When I run the app, nothing happens and nothing is logged. How do I connect to an Azure SQL Database using Node.js?


Solution

  • I found the answer as a comment on another Azure Database issue, provided by @akkonrad. Simply adding a connect statement prior to the provided code from Microsoft, it is now working.

    connection.connect(); //<---- Add This Line ----
    connection.on("connect", err => {
        if (err) {
          console.error(err.message);
        } else {
          queryDatabase();
        }
    });
    

    Hope this prevents someone from digging for hours for the solution.