Is there a way to specify the database when defining Tedious configuration (Node.js)?

1k views Asked by At

According to the Tedious Getting Started Guide, connecting to a database is done like this:

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

      var config = {
        userName: 'test',
        password: 'test',
        server: '192.168.1.210',

        // If you're on Windows Azure, you will need this:
        options: {encrypt: true}
      };

      var connection = new Connection(config);

      connection.on('connect', function(err) {
        // If no error, then good to go...
          executeStatement();
        }
      );

Once a connection has been established, a query can be performed like this:

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

  function executeStatement() {
    request = new Request("select 42, 'hello world'", function(err, rowCount) {
      if (err) {
        console.log(err);
      } else {
        console.log(rowCount + ' rows');
      }
    });

    request.on('row', function(columns) {
      columns.forEach(function(column) {
        console.log(column.value);
      });
    });

    connection.execSql(request);
  }

This works like a charm however, I want to change the request to the following:

 request = new Request("select * from table", function(err, rowCount) {

Obviously, this will not work because there is no database defined in the config object therefore, SQL will not recognise the table.

I have tried adding the following to the config object:

database: 'mydb'

I am still getting the following error:

Invalid object name 'table'.

What is the correct way to define the database in the config object?

2

There are 2 answers

0
Paul On BEST ANSWER

The config object needs to look like this:

var config = {
  userName: 'username',
  password: 'password',
  server: 'server',
  options: {
      database: "databaseName",
  }
};
0
maccaroo On

I'm connecting from NodeJS to a local SQL Server with Tedious. The above config didn't work for me due to how the username/password were specified. The multiple options objects is a little confusing.

In the end, this worked:

var config = {
  server: 'localhost',
  options: {
    database: "randomDB"
  },
  authentication: {
    type: 'default',
    options: {
      userName: 'randomUser',
      password: 'randomPassword'
    }
  }
}