Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connecting to MSSQL server with Sequelize

Using the following tedious code, I can successfully connect to an Azure SQL Server.

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

const connection = new Connection({
    userName: '[USER]',
    password: '[PASSWORD]',
    server: '[HOSTNAME]',
    options: {encrypt: true}
});

connection.on('connect', (err) => {
    if (err) {
        console.log('error connecting', err);
    } else {
        console.log('connection successful');
    }
});

However, using what should be the equivalent Sequelize code, I get a connection timeout error.

const Sequelize = require('sequelize');

const sequelize = new Sequelize('[DBNAME]', '[USER]', '[PASSWORD]', {
    dialect: 'mssql',
    host: '[HOSTNAME]',
    dialectOptions: {
        encrypt: true
    }
});

sequelize.authenticate().then((err) => {
    console.log('Connection successful', err);
})
.catch((err) => {
    console.log('Unable to connect to database', err);
});

Any thoughts?

Using: sequelize 3.29.0, tedious 1.14.0, SQL Server v12

like image 786
Alan Thomas Avatar asked Jan 24 '17 02:01

Alan Thomas


People also ask

Does Sequelize work with mssql?

Sequelize is an easy-to-use and promise-based Node. js ORM tool for Postgres, MySQL, MariaDB, SQLite, DB2, Microsoft SQL Server, and Snowflake. It features solid transaction support, relations, eager and lazy loading, read replication and more.

How do I connect Sequelize in SQL?

The easiest way to do this is using the SQLite dialect: const { Sequelize, Op, Model, DataTypes } = require("sequelize"); const sequelize = new Sequelize("sqlite::memory:"); // Code here!

Can Nodejs connect to SQL Server?

You can connect to a SQL Database using Node. js on Windows, Linux, or macOS.


1 Answers

I was getting below error

SequelizeConnectionError: Server requires encryption, set 'encrypt' config option to true.

I tried it out with Azure SQL Database and below way is working for me.

const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
    host: 'Host',
    dialect: 'mssql',
    dialectOptions: {
        options: {
            encrypt: true,
        }
    }
  });
like image 175
Vinay Bhawsar Avatar answered Sep 26 '22 01:09

Vinay Bhawsar