1

I am unable to execute the sql, when using the global database connection in node.js.

I have followed the steps as in Azure documentation: https://learn.microsoft.com/en-us/azure/mysql/connect-nodejs and able to display the output on the console. But, I want to put all my Azure SQL database connection in a separate file, but the select query is not printing the output on the console.

DatabaseManager.js

var Connection = require('tedious').Connection;
var Request = require('tedious').Request;


var sqlConnection = function sqlConnection() {
// Create connection to database
var config =
  {
    userName: 'uname',
    password: 'password',
    server: 'dbserver.database.windows.net',
    options:
        {
            database: 'mydatabase',
            encrypt: true
        }
  }

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 
    {
        console.log('CONNECTED TO DATABASE');
   }

  }
 );
}
module.exports = sqlConnection;

app.js

var restify = require('restify');
var builder = require('botbuilder');
var botbuilder_azure = require("botbuilder-azure");
var azure = require('azure-storage');
var dbconnection = require('./DatabaseManager');

bot.dialog('profileDialog',
    (session) => {
      session.send('You reached the profile intent. You said \'%s\'.', session.message.text);

      console.log('Reading rows from the Table...');
        dbconnection("select FNAME from StudentProfile where ID=1"),
        function (err, result, fields) {
            if (err) throw err;
            console.log(result);
        }
          session.endDialog();   
    }

Console Output:

Reading rows from the Table...
CONNECTED TO DATABASE

I was expecting the output of FNAME, but nothing is printing on the console. Is there anything, I am missing?

Thank you.

2
  • Why would you think that? At no point do you actually execute that SQL statement. Commented Jan 26, 2019 at 23:27
  • @James, maybe I am wrong in doing that. This is my first js code. I also tried something like dbconnection.query(), but showing invalid method. Any suggestions in correcting this, so the query will execute? Commented Jan 26, 2019 at 23:41

1 Answer 1

3

There's a couple of problems here. First off, you should only ever import a module once per file. This is just a performance consideration and won't actually break your code.

Next, pay attention to what you're exporting from your DatabaseManager module. Right now, you're exporting a function that creates the connection and then doesn't do anything with it. We can fix this by using a pattern called a "callback" which lets us provide a function that will then be called with the connection as an argument.

I added a ton of comments to the code explaining things. This code won't run as-is - there's a couple places where I have "do this or this". You'll have to choose one.

var Tedious = require('tedious'); // Only require a library once per file
var Connection = Tedious.Connection;
var Request = Tedious.Request;

// Or using the object spread operator
var { Connection, Request } = require('tedious');

// You called this `sqlConnection`. I'm going to use a verb since it's a
// function and not a variable containing the connection. I'm also going
// to change the declaration syntax to be clearer.

function connect(cb) { // cb is short for callback. It should be a function.
  var config = {
    userName: 'uname',
    password: 'password',
    server: 'dbserver.database.windows.net',
    options: {
      database: 'mydatabase',
      encrypt: true
    }
  }; // Put a semi-colon on your variable assignments

  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);
      return; // Stop executing the function if it failed
    }

    // We don't need an "else" because of the return statement above
    console.log('CONNECTED TO DATABASE');

    // We have a connection, now let's do something with it. Call the
    // callback and pass it the connection.
    cb(connection);
  });
}

module.exports = connect; // This exports a function that creates the connection

Then back in your main file, you can use it like so.

var restify = require('restify');
var builder = require('botbuilder');
var botbuilder_azure = require('botbuilder-azure');
var azure = require('azure-storage');
var connect = require('./DatabaseManager'); // renamed to be a verb since it's a function.

bot.dialog('profileDialog', (session) => { // Hey, this is a callback too!
  session.send('You reached the profile intent. You said \'%s\'.', session.message.text);

  console.log('Creating a connection');

  connect((connection) => {
  // or with the traditional function notation
  connect(function(connection) {

    console.log('Reading rows from the Table...');

    // Execute your queries here using your connection. This code is
    // taken from 
    // https://github.com/tediousjs/tedious/blob/master/examples/minimal.js
    request = new Request("select FNAME from StudentProfile where ID=1", function(err, rowCount) { // Look another callback!
    if (err) {
      console.log(err);
    } else {
      console.log(rowCount + ' rows');
    }
    connection.close();
  });

  request.on('row', function(columns) {  // Iterate through the rows using a callback
    columns.forEach(function(column) {
      if (column.value === null) {
        console.log('NULL');
      } else {
        console.log(column.value);
      }
    });
  });

  connection.execSql(request);
});
Sign up to request clarification or add additional context in comments.

6 Comments

Can you please give an example, to execute the query using the connection in the above app.js ?
Thanks 3ocene, there is a missing line which executes the sql. For some reason, I need to again include the tedious things again in the app.js. Otherwise, I am getting, Request is not defined.
Thanks for editing in the line I missed! And yes that's correct. When you import something, it's only available in that file, not any file that includes it. If A imports B imports C, A can access B, B can access C, but A cannot access C.
const/let over var, Promises over callbacks, and offering equivalent code as options is just muddying the example, arrow functions over STD functions where appropriate.
@James, without knowing what version of Node OP is running, I don't want to do anything that will cause the example to break. I do, however, want to discourage anyone from copy-pasting the code without reading it. If there's a style guide for stack overflow that I'm not aware of, I'd be happy to adhere to it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.