Fork me on GitHub

Getting started

In this introduction, error handling, and some other details are glossed over.

Connecting to the database looks like this.

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

  var config = {
    server: "192.168.1.210",
    options: {},
    authentication: {
      type: "default",
      options: {  
        userName: "test",
        password: "test",
      }
    }
  };

  var connection = new Connection(config);

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

The arguments to the Connection constructor are host, username, password, an options object (empty in this example), and a callback function.

Tedious will use an encrypted connection by default from v6.0.0 onwards. If you have an earlier version, and require encryption or use Windows Azure, you must set {encrypt: true} within the options object. Similarly, if you need an unencrypted connection, you must explicitly set {encrypt: false} within the options object.

The connect event is emitted when either the connection has been established and authentication has succeeded, or an error occurred during connection or authentication.

Once a connection has been established, a query can be executed.

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

A request is represented by a Request instance. The arguments to Request's constructor are the SQL statement, and a callback function. The callback is called if an error occurs.

A row event is emitted for each row returned as a result of executing the statement. An array of columns is the sole parameter to the callback. For each column, a value and metadata is provided (although only the value is used in this example).

When the request is complete, the callback is called.

To execute the statement, the Connection's execSql must be called.

An example based around these code fragments can be found in examples/minimal.js .


Azure Data Warehouse Connection

Connecting to Azure Data Warehouse requires specifying additional config options:

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

  var config = {
    userName: 'test',
    password: 'test',
    server: '192.168.1.210',
    
    // If you're on Azure Data Warehouse, you will need this:
    options: {
      encrypt: true,
      enableArithAbort: true,
      connectionIsolationLevel: ISOLATION_LEVEL.READ_UNCOMMITTED
    }
  };

  var connection = new Connection(config);